题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路:
后续遍历时,遍历到一个节点,其左右子树已经遍历,依次自底向上判断,每个节点只需要遍历一次。
public class Solution {
private boolean isBalanced = true;
public boolean IsBalanced_Solution(TreeNode root) {
getDepth(root);
return isBalanced;
}
private int getDepth(TreeNode node)
{
if (node == null) return 0;
int left = getDepth(node.left);
int right = getDepth(node.right);
if (Math.abs(left - right) > 1)
isBalanced = false;
return Math.max(left,right) + 1;
}
}
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return isBalanced(root, new int[1]);
}
private boolean isBalanced(TreeNode node, int[] depth)
{
if (node == null)
{
depth[0] = 0;
return true;
}
boolean left = isBalanced(node.left,depth);
int leftDepth = depth[0];
boolean right = isBalanced(node.right, depth);
int rightDepth = depth[0];
depth[0] = Math.max(leftDepth, rightDepth) + 1;
if (left && right && Math.abs(leftDepth - rightDepth) <= 1) return true;
return false;
}
}