【LeetCode 110_二叉樹_遍歷】Balanced Binary Tree

QingLiXueShi發表於2015-07-05

解法一:From top to bottom

 1 int treeHeight(TreeNode *T)
 2 {
 3     if (T == NULL)
 4         return 0;
 5     
 6     return max(treeHeight(T->left), treeHeight(T->right)) + 1;
 7 }
 8 
 9 bool isBalanced(TreeNode* root)
10 {
11     if (root == NULL)
12         return true;
13 
14     int left_height = treeHeight(root->left);
15     int right_height = treeHeight(root->right);
16     if (abs(left_height - right_height) > 1)
17         return false;
18 
19     if (!isBalanced(root->left) || !isBalanced(root->right))
20         return false;
21 
22     return true;
23 }

解法一遞迴判斷子樹是否為平衡二叉樹的過程中,重複計算了多次子樹的高度,時間複雜度大於O(N)。解法二將這個計算過程優化了,時間複雜度為O(N)。

解法二:From bottom to top

 1 int dfsTreeHeight(TreeNode *T)
 2 {
 3     if (T == NULL)
 4         return 0;
 5 
 6     int left_height = dfsTreeHeight(T->left);
 7     if (left_height == -1)
 8         return -1;
 9     int right_height = dfsTreeHeight(T->right);
10     if (right_height == -1)
11         return -1;
12     if (abs(left_height - right_height) > 1)
13         return -1;
14 
15     return max(left_height, right_height) + 1;
16 }
17 
18 bool isBalanced(TreeNode* root)
19 {
20     if (root == NULL)
21         return true;
22 
23     return dfsTreeHeight(root) != -1;
24 }

 

相關文章