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 every node never differ by more than 1.
Tree Depth-first Search
题意:判断一棵二叉树是否为平衡二叉树
thinking:
(1)这道题以为很简单,但是仔细研究才发现,对平衡二叉树的理解有误:左右子树的最大深度(即树高)之差不超过1,
不是特指每个叶子节点的高度,是树的高度。我一开始是求出每个叶子节点的高度,再比较,这么做不符合平衡二叉树的定义
(2)准确思路是递归 每次对左右子树进行判断。
code:
错误思路:
class Solution {
private:
vector<int> depth;
public:
bool isBalanced(TreeNode *root) {
if(root==NULL)
return true;
dfs(0,root);
sort(depth.begin(),depth.end());
if(*(depth.end()-1)-depth[0]>1)
return false;
else
return true;
}
protected:
void dfs(int dep,TreeNode *node)
{
if(node==NULL)
{
cout<<dep<<endl;
depth.push_back(dep);
return;
}
dep++;
dfs(dep,node->left);
dfs(dep,node->right);
}
};
正确答案:
class Solution {
public:
bool isBalanced(TreeNode *root) {
int depth = 0;
return isbalance(root, depth);
}
bool isbalance(TreeNode *root, int &depth)
{
if(root == NULL)
{
depth = 0;
return true;
}
int ld,rd;
if( isbalance(root->left,ld) && isbalance(root->right,rd))
{
if( abs(ld - rd) > 1)
{
return false;
}
depth = ld > rd ? ld + 1 : rd + 1;
return true;
}
}
};