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.
这个题是经典的考察对树结构和递归理解的题。。6个月前刚开始刷leetcode,这个题我楞是没做出来,看了同学的代码,好简洁,只觉得为啥自己想不出来。如果有谁刚开始刷题,一些简单的题也没做好,别灰心。这个题如果没想出来,那一定是对递归,和树的遍历理解不透彻,多思考多理解即可。
以下这段代码是楼主6月前,算法还给了老师,思维逻辑混乱,写成了这样。
public class Solution {
public boolean isBalanced(TreeNode root) {
TreeNode tree=root;
if(tree==null) return true;
else{
if((tree.left==null&&tree.right==null)) return true;
else if(tree.left!=null&&tree.right!=null){
return isBalanced(tree.left)&&isBalanced(tree.right);
}
else if(tree.left==null&&tree.right!=null){
if(tree.right.left!=null||tree.right.right!=null){ return false;}
else return true;
}
else {
if(tree.left.left!=null||tree.left.right!=null){ return false;}
else return true;
}
}
}
}
经过了其他树和递归问题的吊打,形成了这样的思路:
要求树是否平衡:1. 平衡就是左右两边的深度depth不超过1 2. 左子树和右子树也得平衡
所以那我们如果要求递归,不能在isBalanced这个函数中返回depth了,所以再写一个小函数,算深度。如题 Maximum depth of binary tree
关键点分析完,那如何实现,也就是说,哪种方法遍历树呢? 由题意所知,必须知道左子树和右子数的深度才可以求出来root为根节点的树是否平衡。 那必须是postOrder后序遍历了。所以代码中 return的那一串是“左,右,根节点”的简写。
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return isBalanced(root.left)&& isBalanced(root.right)&&
(Math.abs(depth(root.left)-depth(root.right))<=1);
}
public int depth(TreeNode root){
if(root==null) return 0;
int left=depth(root.left);
int right=depth(root.right);
return Math.max(left,right)+1;
}
}
今天发现,上面那段代码不是最好的,因为:每一个节点其实都有一个寻找depth的方法。这样的话时间复杂度是 O(N log H), N 是树节点的数量,H是树的高度。
其实有 O(N)的时间就足够了——在每次计算depth的时候,我们如果发现了有不平衡的树,就直接返回,而不去执行下面的代码。
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return TreeHeight(root)!=-1;
}
public int TreeHeight(TreeNode root){
if(root==null) return 0;
int left=TreeHeight(root.left);
if(left==-1) return -1;
int right=TreeHeight(root.right);
if(right==-1) return -1;
if(Math.abs(left-right)>1) return -1;
else return Math.max(left,right)+1;
}
}