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.
思路1:使用自动向下的递归,每次递归都要计算左右子树的高度。若根节点是平衡的,则看其左右节点是否是平衡的,不断的递归。这样有重复。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root){
if(root==null) return 0;
int maxleft=maxDepth(root.left);
int maxright=maxDepth(root.right);
return 1+(maxleft>maxright?maxleft:maxright);
}
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int leftdepth=maxDepth(root.left);
int rightdepth=maxDepth(root.right);
if(Math.abs(leftdepth-rightdepth)>1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
}
思路2:如果我们用后序遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们已经遍历了它的左右子树。 只要在遍历每个结点的时候记录它的深度(某一结点的深度等于它到叶节点的路径的长度), 我们就可以一边遍历一边判断每个结点是不是平衡的
由于Java无法像C那样“传递参数的地址,函数返回时能得到参数的值”,我们只能新建一个静态的内部类:Depth
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static class Depth{
private int depth;
}
public boolean isBalanced(TreeNode root, Depth d) {
if (root == null) {
d.depth = 0;
return true;
}
Depth left=new Depth();
Depth right=new Depth();
if (isBalanced(root.left, left) && isBalanced(root.right, right)) {
int diff = left.depth - right.depth;
if ((diff > 1) || (diff < -1)) {
return false;
}
d.depth = 1 + (left.depth > right.depth ? left.depth : right.depth);
return true;
}
return false;
}
public boolean isBalanced(TreeNode root) {
Depth temp=new Depth();
return isBalanced(root,temp);
}
}