Balanced_Binary_Tree

判断是否是平衡二叉树

QuestionEditorial Solution My Submissions
Total Accepted: 147366
Total Submissions: 408360
Difficulty: Easy
Contributors: Admin
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.
Subscribe to see which companies asked this question

平衡二叉树:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
如何解决这道题目一个思路就是按照递归的思路去做。先去判读根节点的左右两边的深度差是否大于1,小于的话再去判断他的子树是否为平衡二叉树。这里就要借助递归。

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

一开始我觉得这种算法很顺手的,思考的时候也很简单。但是我后来在leetcode上测了下时间有快20ms,就觉得有问题,原来一看这里又两层递归就是递归里面套递归,所以花费时间很长时间在这里面。
这种算法的时间复杂度为nlogn所以大量时间花费在了算书的深度上。
然后上网查了下有如下的算法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool isBalanced(TreeNode* root) {
// write code here
int high=0;
return isBalance1(root,high);
}
bool isBalance1(TreeNode* root,int &high)
{
if(root==NULL)
{
high=0;
return true;
}
int lhigh,rhigh;
if(!isBalance1(root->left,lhigh)||!isBalance1(root->right,rhigh))
return false;
if(lhigh-rhigh>1||lhigh-rhigh<-1)
return false;
high=(lhigh>=rhigh?lhigh:rhigh)+1;
return true;
}
};

这种算法就用了一层递归,高度的递归在算平衡里面已经解决了,所以速度要比上面的要快。

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×