题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
思路:
- 所谓平衡二叉树,如果每个节点的左右两子树深度差绝对值不超过1;
- 递归;以一个最普通的二叉树思考,该节点的|左子树深度 -左子树深度|<=1,且它的左子树和右子树也满足-->递归
- 如何获取该节点的深度,这里又是另外一个递归,以一个最普通的二叉树思考:
leftHight >= rightHight ? leftHight + 1 : rightHight + 1;
代码
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
if(root!=null){
int leftHight = TreeDepth(root.left);
int rightHight = TreeDepth(root.right);
if(leftHight -rightHight < - 1 || leftHight -rightHight >1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
return true;
}
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftHight = TreeDepth(root.left);
int rightHight = TreeDepth(root.right);
return leftHight >= rightHight ? leftHight + 1 : rightHight + 1;
}
}
网友评论