平衡二叉树
平衡二叉树
http://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222
1、空数
2、求root的左右子树的深度,左右子树的深度 差在 1以内
public boolean IsBalanced_Solution(TreeNode root) { if(root == null) return true; int l = 0; if(root.left != null) { l = depth(root.left); } int r = 0; if(root.right != null) { r = depth(root.right); } return Math.abs(l - r) > 1 ? false : true; } /** * 求一棵树的深度 * @param node * @return */ public int depth(TreeNode node) { int legnth = 0; if(node.left!=null || node.right!=null) { legnth ++; } int l = 0; if(node.left != null) { l = depth(node.left); } int r = 0; if(node.right != null) { r = depth(node.right); } legnth += (l >= r ? l : r); return legnth; } public boolean MLR(TreeNode node) { if(!helpBalanced(node)){ return false; } if(node.left != null) { MLR(node.left); } if(node.right != null) { MLR(node.right); } return true; } public boolean helpBalanced(TreeNode node) { int leftHigh = 0; int rightHigh = 0; if(node.left != null) { leftHigh ++; if(node.left.left != null || node.left.right != null) { leftHigh ++; } } if(node.right != null) { rightHigh ++; if(node.right.left != null || node.right.right != null) { rightHigh ++; } } return Math.abs(rightHigh - leftHigh) > 1 ? false : true; }