标签:style blog io color ar for sp div on
这几天A的都是二叉树的,如果输的基本操作掌握了,用递归很好解决这些题目的。这个可能不是最好的解法,明天再去Discuss看看有没有好的解法
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 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 /** 12 * 这里用递归实现 13 * 如果为空节点返回true 14 * 如果不为空比较左右子树的高度,如果高度差的绝对值小于等于1且左右子树都是平衡二叉树return true 15 * @param root 16 * @return 17 */ 18 public boolean isBalanced(TreeNode root){ 19 if(null == root){ 20 return true; 21 }else 22 { 23 return (Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right); 24 } 25 26 } 27 /** 28 * 获取一棵树的高度 29 * 递归获取 30 * @param root 31 * @return 32 */ 33 public int getHeight(TreeNode root){ 34 if(null == root) 35 return 0; 36 else{ 37 int max = getHeight(root.left); 38 if(max < getHeight(root.right)) 39 { 40 max =getHeight(root.right); 41 } 42 return max + 1; 43 } 44 } 45 }
标签:style blog io color ar for sp div on
原文地址:http://www.cnblogs.com/luckygxf/p/4077499.html