leetcode------Balanced Binary Tree

标题:

Balanced Binary Tree

通过率: 32.3%
难度: 简单

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.

平衡二叉树。这个可以由二叉树深度来计算,再二叉树深度计算中每次进行深度比较取深度较深的一个,那么平衡二叉树再比较深度时就是A-B绝对值超过一的话就不是二叉树了。立马返回-1 ,当左右子树有一边深度值是-1时立马终止,返回此树非平衡二叉树,如果A-B绝对值总是在0,1,-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     public boolean isBalanced(TreeNode root) {
12         if(root==null) return true;
13         if(height(root)==-1) return false;
14         else return true;
15         
16     }
17     public int height(TreeNode root){
18         if(root==null) return 0;
19         int depth1=0;
20         int depth2=0;
21         depth1=height(root.right);
22         depth2=height(root.left);
23         if(depth1==-1||depth2==-1) return -1;
24         if((depth1-depth2>1 )||(depth1-depth2)<-1)
25             return -1;
26         else{
27              if(depth1>depth2)
28             return depth1+1;
29             else
30                 return depth2+1;
31         }
32             
33     }
34 }

 

posted @ 2014-12-18 13:45  pku_smile  阅读(138)  评论(0编辑  收藏  举报