leetcode 110. 平衡二叉树(判断是否为平衡二叉树)
题意:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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 。
思路:
什么是平衡二叉平衡树?
左右子树的深度差的绝对值不大于1
左子树和右子树也都是平衡二叉树
所以我们只需要在求一棵树的深度的代码中加上高度差判断就可以
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int judge(TreeNode* root,bool &ans)
{
if(root)
{
int ans1 = judge(root->left,ans);
int ans2 = judge(root->right,ans);
if(abs(ans1-ans2)>1) ans=false;
return max(ans1,ans2)+1;
}
else return 0;
}
bool isBalanced(TreeNode* root) {
bool ans = true;
judge(root,ans);
return ans;
}
};


浙公网安备 33010602011771号