Balanced Binary Tree -- LeetCode

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.

思路:这题有两种方法。

Top down approach

设计一个depth函数,递归地返回一个子树的深度。

一个BST平衡的条件为:为空;或者左右子树皆平衡,且左右子树的深度相差不超过1。

 1 class Solution {
 2 public:
 3     int depth(TreeNode *root)
 4     {
 5         if (!root) return 0;
 6         return max(depth(root->left), depth(root->right)) + 1;
 7     }
 8     bool isBalanced (TreeNode *root) {
 9         if (!root) return true;
10         int left = depth(root->left);
11         int right = depth(root->right);
12         return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); 
13     }
14 };

复杂度分析:

用master theory: depth函数为T(n) = 2T(n/2) + 1,为O(n);

isBalanced函数为T(n) = 2T(n/2) + O(n),为O(nlogn)。

如果这种方法想让时间复杂度降为O(n),则需要用map记录下每个子树的深度,以后就不需要再计算了。但空间复杂度为O(n)。

Bottom up approach

自底向上进行判断。使用一个help函数,若子树为平衡的,则返回该子树的深度,否则返回0。该方法每个节点只访问一遍,因此复杂度为O(n)。

 1 class Solution {
 2 public:
 3     int help(TreeNode *root)
 4     //balanced -- result >= 0
 5     //not balanced -- result = -1
 6     {
 7         if (!root) return 0;
 8         int left = help(root->left);
 9         if (left == -1) return -1;
10         int right = help(root->right);
11         if (right == -1) return -1;
12         if (abs(left - right) > 1) return -1;
13         return max(left, right) + 1;
14     }
15     bool isBalanced (TreeNode *root) {
16         return help(root) != -1;
17     }
18 };

 

posted @ 2016-01-29 04:45  fenshen371  阅读(124)  评论(0编辑  收藏  举报