110.平衡二叉树
思路
1.直接能够想出来是通过求左右两颗子树的深度,相减后来判断当前节点是否是平衡的,再递归其左右子树。时间复杂度O(NlogN)。
2.题解利用了后序遍历+剪枝(从底至顶),按照后序遍历节点的顺序,依次判断是否是平衡,并记录该节点的深度递归返还给上一层节点.利用-1来记录非平衡。时间复杂度为O(N)。这个方法很难想到(自底向上),想到了又很难写出来(递归的终止条件)。
代码
1
class Solution {
public boolean isBalanced(TreeNode root) {
if (root==null) return true;
if (Math.abs(depth(root.left)-depth(root.right))>1) return false;
return isBalanced(root.right) && isBalanced(root.left);
}
public int depth(TreeNode root){
if (root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
return recur(root)!=-1;
}
public int recur(TreeNode root){
if (root==null) return 0;
int left=recur(root.left);
if (left==-1) return -1;
int right=recur(root.right);
if (right==-1) return -1;
return Math.abs(left-right) <= 1 ? Math.max(left,right)+1 : -1;
}
}