leetcode--Balanced Binary Tree

来源:互联网 发布:手机里网络错误怎么办 编辑:程序博客网 时间:2024/06/08 10:50

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 ofevery node never differ by more than 1.


题意:判断一棵树是否是平衡二叉树。

分类:二叉树


解法1:计算递归左右子树的深度,比较这两个深度,如果相等或者相差1,则递归判断左右子树是否平衡。

如果不符合平衡二叉树条件,则返回假。

[java] view plain copy
  1. /** 
  2.  * Definition for a binary tree node. 
  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==nullreturn true;  
  13.         int dis = Math.abs(getDepth(root.left)-getDepth(root.right));  
  14.         if(dis>=0&&dis<=1){  
  15.             return isBalanced(root.left)&&isBalanced(root.right);  
  16.         }  
  17.         return false;  
  18.     }  
  19.       
  20.     public int getDepth(TreeNode p){  
  21.         if(p==nullreturn 0;  
  22.         else{  
  23.             int left = getDepth(p.left);  
  24.             int right = getDepth(p.right);  
  25.             return left>right?left+1:right+1;  
  26.         }  
  27.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46378853

原创粉丝点击