平衡二叉树-Java实现
平衡二叉树
http://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222
一. 思路
自底向上解法:按照平时做纸质考试的去思考如何判断一颗树是否平衡。采用后序遍历用自底向上递归方法,计算(左子树的深度-右子树的深度)的绝对值是否小于1,若是则平衡。
自顶向下解法:采用前序遍历一次树,计算每个节点的深度并存到map中。第二次遍历树,计算高度差是否符合平衡的要求
二. 递归解法的代码
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return depthOfNode(root) != -1;
}
public int depthOfNode(TreeNode root) {
if (root == null) return 0;
int leftDepth = depthOfNode(root.left);
if (leftDepth == -1) return -1;
int rightDepth = depthOfNode(root.right);
if (rightDepth == -1) return -1;
if ((leftDepth - rightDepth) < -1 || (leftDepth -rightDepth) > 1) {
return -1;
} else {
return 1 + (leftDepth > rightDepth ? leftDepth : rightDepth);
}
}
}
查看23道真题和解析