[LeetCode]110. Balanced Binary Tree

Problem

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 everynode never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1
2
3
4
5
6
7
      1
/ \
2 2
/ \
3 3
/ \
4 4

Return false.

Solution

解析

根据平衡二叉树定义,每个节点子树之间的高度差不能超过1.所以我们先定义一个求二叉树高度的函数getDepth(),然后递归对二叉树节点进行判断。

Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
int left = getDepth(root->left), right = getDepth(root->right);

if ( left - right > 1 || right - left > 1) return false;

return isBalanced(root->left) && isBalanced(root->right);
}
private:
int getDepth(TreeNode* root){
if (!root) return 0;
int left = getDepth(root->left);
int right = getDepth(root->right);

return max(left, right) + 1;
}
};

这种方法速度比较慢。原因在于,节点高度的重复计算。自上而下,节点的高度多次重复计算,提高了时间复杂度。

如果简化的话,想办法自下而上,减少重复计算。这里,修改getDepth()函数,让函数在求二叉树深度的同时,判断左右节点的高度差,如果大于1,返回-1(说明这棵二叉树一定不是平衡二叉树,及时停止)。

Solution 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return dfsDepth(root) != -1;
}
private:
int dfsDepth(TreeNode* root){
if (!root) return 0;
int left = dfsDepth(root->left);//递归函数
int right = dfsDepth(root->right);

if (left == -1 || right == -1) return -1;//子树不是avl
if (abs(left - right) > 1) return -1;//当前树不是avl

return max(left, right) + 1;
}
};
您的支持就是我更新的最大动力!谢谢!