首页 > 代码库 > Balanced Binary Tree

Balanced Binary Tree

这几天A的都是二叉树的,如果输的基本操作掌握了,用递归很好解决这些题目的。这个可能不是最好的解法,明天再去Discuss看看有没有好的解法

Balanced Binary Tree

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      * 如果为空节点返回true14      * 如果不为空比较左右子树的高度,如果高度差的绝对值小于等于1且左右子树都是平衡二叉树return true15      * @param root16      * @return17      */18     public boolean isBalanced(TreeNode root){19         if(null == root){20             return true;21         }else22         {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 root31      * @return32      */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 }

 

Balanced Binary Tree