LeetCode上有一道题,链接在此:http://leetcode.com/onlinejudge#question_110
题目要求很简单,给你一个二叉树,让你判断这个二叉树是不是balanced。这里对于balanced的定义是:树里的每一个点的左右两个subtree的depth之差不超过一。
跟大部分的二叉树的题一样,这道题也需要用递归的方法。
一个比较intuitive的递归方法如下:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(0), right(0) {}
};
class Solution {
int findHeight(TreeNode *root) {
if (!root) return 0;
return std::max(findHeight(root->left), findHeight(root->right)) + 1;
}
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root) return true;
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);
if (fabs(leftHeight - rightHeight) > 1) return false;
bool leftResult = isBalanced(root->left);
bool rightResult = isBalanced(root->right);
return (leftResult && rightResult);
}
};
可以看到,这就是严格遵循题目中对于”Balanced"这个词的定义:先找到左右两个subtree的高度,然后比较,看看他们的差是否大于一。如果不大于一,则recursively对左右两个children进行相同的过程。
这个方法的问题也是显而易见的,那就是每个node访问了过多次。首先,除了root以外,每一个点都要算一次高度;一个高度为k的点,在计算每一个k+1点的时候,都要被访问一次。这个方法的复杂度是O(nlogn)。
一个更好的方法如下:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(0), right(0) {}
};
class Solution {
int findHeight(TreeNode *root) {
if (!root) return 0;
return std::max(findHeight(root->left), findHeight(root->right)) + 1;
}
int isBalancedHelper (TreeNode* root) {
if (!root) return 0;
int l = isBalancedHelper (root->left);
int r = isBalancedHelper (root->right);
if (l < 0 || r < 0 || (l - r > 1) || (r - l) > 1) return -1;
return (std::max(l, r) + 1);
}
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return isBalancedHelper(root) != -1;
}
};
这个方法的核心function是isBalancedHelper()。这个函数的本质其实是计算一个点的height,只不过它很巧妙地把-1这个值作为一个特别的值来表示是否balance。即,如果是balanced,则返回高度;如果不是balanced,则返回-1。而且很容易看到的是,这个函数的复杂度为O(n)。
但奇特的是,我把两种方法都在LeetCode的服务器上跑了一下,发现方法二的用时是116毫秒,而方法一的则是108毫秒。时间复杂度高的程序反而跑得更快。。
或许是LeetCode这道题的data set选取有点问题吧。
如果能有人能指出问题之所在,不胜感激~