判断二叉树是否为平衡二叉树

  1. //用递归的思想,先判断总体是否平衡,再递归判断左子树和右子树
  2. public class Solution {  
  3.     public boolean IsBalanced_Solution(TreeNode root) {  
  4.         if(root==null)  
  5.             return true;  
  6.         int left=depth(root.left);  
  7.         int right=depth(root.right);  
  8.         if(Math.abs(left-right)>1)  
  9.             return false;  
  10.            
  11.         boolean booleft=IsBalanced_Solution(root.left);  
  12.         boolean booright=IsBalanced_Solution(root.right);  
  13.         return booleft&&booright;  
  14.     }  
  15.    
  16.     public int depth(TreeNode root){  
  17.         if(root==null)  
  18.             return 0;  
  19.         int left=depth(root.left);  
  20.         int right=depth(root.right);  
  21.         return (left>right)?(left+1):(right+1);  
  22.     }  
  23. }  
posted @ 2018-03-14 17:34  零。幺  阅读(262)  评论(0编辑  收藏  举报