剑指offer 平衡二叉树

题目:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

 

分析:首先理解什么是平衡二叉树。平衡二叉树具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

 

很明显可以用递归解决。

解法一:

 1 class Solution {
 2 public:
 3     int depth(TreeNode *pRoot) {
 4         if (pRoot == nullptr) {
 5             return 0;
 6         }
 7         int left = depth(pRoot->left);
 8         int right = depth(pRoot->right);
 9         return max(left, right) + 1;
10     }
11     bool IsBalanced_Solution(TreeNode* pRoot) {
12         if (pRoot == nullptr) {
13             return true;
14         }
15         int left = depth(pRoot->left);
16         int right = depth(pRoot->right);
17         return (abs(left - right) <= 1 && IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right));
18     }
19 };

上述解法的不足在于在计算上层节点的时候,他会反复计算下层节点的深度,增加了时间复杂度,于是有了后序遍历的解法,先判断两个子树是否为平衡二叉树,是的话返回深度,否则标记为1.

解法二:后序遍历

 1 class Solution {
 2 private:
 3     int getdepth(TreeNode *pRoot) {
 4         if (pRoot == NULL) {
 5             return 0;
 6         }
 7         int left = getdepth(pRoot->left);
 8         if (left == -1) {
 9             return -1;
10         }
11         int right = getdepth(pRoot->right);
12         if (right == -1) {
13             return -1;
14         }
15         return abs(left - right) > 1 ? -1 : 1 + max(left, right);
16     }
17 public:
18     bool IsBalanced_Solution(TreeNode* pRoot) {
19         return getdepth(pRoot) != -1;
20     }
21 };

 

posted @ 2019-03-05 00:51  琴影  阅读(158)  评论(0编辑  收藏  举报