[面试真题] LeetCode:Balanced Binary Tree

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

递归地计算每个节点的左右子树深度,看其是否平衡。由于节点被重复访问,效率较低。

Program Runtime: 68 milli secs

 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     
12         
13     int maxDepth(TreeNode *root){
14         if(NULL == root){
15             return 0;
16         }
17         int maxL = maxDepth(root->left);
18         int maxR = maxDepth(root->right);
19         return 1 + (maxL > maxR ? maxL : maxR);
20     }
21     
22 public:
23     bool isBalanced(TreeNode *root) {
24         // Start typing your C/C++ solution below
25         // DO NOT write int main() function
26         if(NULL == root){
27             return true;
28         }
29         int diff = maxDepth(root->left) - maxDepth(root->right);
30         if((diff>1) || (diff<-1)){
31             return false;
32         }
33          return isBalanced(root->left) && isBalanced(root->right);
34     }
35 };

改进:使用后序遍历二叉树的节点,遍历时记录节点深度,同时也可以更快的判断出二叉树不平衡的情况。

可是奇怪的是执行时间反而变长了,不解。

Program Runtime: 84 milli secs

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

 

posted @ 2013-05-11 21:21  infinityu  阅读(2870)  评论(0编辑  收藏  举报