给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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.com/problems/balanced-binary-tree
class Solution {
private boolean result = true;
public boolean isBalanced(TreeNode root) {
height(root);
return result;
}
public boolean height(TreeNode root){
if(root == null) return 0;
int r = height(root.left);
int l = hright(root.right);
if(Math.abs(l-r)>1) return false;
return 1+Math.max(l,r);
}
}
本文地址:https://blog.csdn.net/weixin_43515720/article/details/107676873
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论