方法:后序遍历输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/
9 20
/
15 7
返回 true 。示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/
2 2
/
3 3
/
4 4
返回 false 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof
递归函数helper的作用是判断以root为根节点的二叉树的左右子树深度的差值是否超过1。
思路是对二叉树做后序遍历,自顶向上返回子树深度,若判定某子树不是平衡树,就一直返回-1。如果是平衡树的话,就返回子树深度。这里的子树深度是用左子树和右子树深度的最大值+1来计算的,本来我是用先序depth++,后序depth--来计算的,结果发现这样子无法正确返回深度。
时间复杂度是 O(n)
class Solution {
public:
int depth=0;
bool isBalanced(TreeNode* root) {
if(!root)
return true;
return(helper(root)!=-1);
}
// 以root为根节点的二叉树的左右子树深度的差值是否超过1
int helper(TreeNode* root)
{
if(root==NULL)
return 0;
// depth++;
int leftdepth=helper(root->left);
int rightdepth=helper(root->right);
if(abs(leftdepth-rightdepth)<=1 && leftdepth>=0 && rightdepth>=0)
return max(leftdepth,rightdepth)+1;
else
return -1;
// if(abs(leftdepth-rightdepth)>1 || leftdepth==-1 || rightdepth==-1)
// return -1;
// depth--;
// return depth;
}
};


