Leetcode::Balanced Binary Tree

后序遍历,每个节点只遍历一次。

 1 /**
 2  * Definition for binary tree
 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 class Solution {
11 public:
12     bool BalanceTree( TreeNode *root,int &depth )
13     {
14         if( root == NULL )
15         {
16             depth = 0;
17             return true;
18         }
19         int left,right;
20         if( BalanceTree(root->left,left) && BalanceTree(root->right,right) )
21         {
22             int dif = left - right;
23             if( dif >= -1 && dif <= 1 )
24             {
25                 depth = max(left,right) + 1;
26                 return true;
27             }
28         }
29         return false;
30     }
31     bool isBalanced(TreeNode *root) {
32         // Start typing your C/C++ solution below
33         // DO NOT write int main() function
34         int depth=0;
35         return BalanceTree(root,depth);
36     }
37 };

 

posted @ 2013-07-27 18:45  NinaGood  阅读(155)  评论(0编辑  收藏  举报