1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 
11 static int wing=[]()
12 {
13     std::ios::sync_with_stdio(false);
14     cin.tie(NULL);
15     return 0;
16 }();
17 
18 
19 
20 class Solution 
21 {
22 public:   
23     const int UNBALANCED=-66;
24     bool isBalanced(TreeNode* root) 
25     {
26         if(root==NULL)
27             return true;
28         return getHeight(root)!=UNBALANCED;
29     }
30     
31     int getHeight(TreeNode* T)
32     {
33         if(T==NULL)
34             return 0;
35         int l=getHeight(T->left);
36         int r=getHeight(T->right);
37         if(l==UNBALANCED||r==UNBALANCED||abs(l-r)>1)
38             return UNBALANCED;
39         return 1+max(l,r);
40     } 
41 };

递归判断左右子树,只要有一个节点不平衡,则整棵树不平衡

posted on 2018-04-19 13:18  高数考了59  阅读(98)  评论(0)    收藏  举报