题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:最长路径和最短路径相差小于等于1,考虑特殊情况根节点的左子树或右子树为空。

ac代码:

 1 public class Solution {
 2     public boolean IsBalanced_Solution(TreeNode root) {
 3         if(root==null)
 4             return true;
 5         dfs(root,0);
 6         if(max==min&&max>1&&root.right==null)
 7             return false;
 8         if(max==min&&max>1&&root.left==null)
 9             return false;
10         if(min==max||min+1==max)
11             return true;
12         else
13             return false;
14     }
15     int max=0;
16     int min=99999999;
17      void  dfs(TreeNode root,int t){
18         t++;
19         if(root.left==null&&root.right==null){
20             max=Math.max(max, t);
21             min=Math.min(min, t);
22         }
23         if(root.left!=null){
24             dfs(root.left,t);
25         }
26         if(root.right!=null){
27             dfs(root.right,t);
28         }
29     }
30 }

 

 posted on 2018-04-12 18:36  几缕清风依旧  阅读(115)  评论(0编辑  收藏  举报