题目
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
我的尝试
用递归的思路,前面写过一个就二叉树最大深度的算法,利用递归计算出左子树和右子树的最大深度,判断abs绝对值是否小于等于1.代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode node){
if(node==null) return 0;
return Math.max(maxDepth(node.left),maxDepth(node.right))+1;
}
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1;
}
}
但是有问题,我理解的情况有偏差,如果下面的情况不正确,因为节点2的左子树是3,4但是右子树为空。
我这个算法,比较的是左侧的最大深度和右侧的最大深度差值,如果是左侧的两个深度比较呢?显然没有覆盖这个情况。
下面进行修改:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDep(TreeNode node){
if(node==null) return 0;
return 1+Math.max(maxDep(node.left),maxDep(node.right));
}
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int diff=Math.abs(maxDep(root.left)-maxDep(root.right));
if(diff>1){
return false;
}
return isBalanced(root.left)&& isBalanced(root.right);
}
}