题目:
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.
给定一个二叉树,判断它是否是平滑二叉树。具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
解题思路:
如果我们用从下至上遍历的方式遍历二叉树的每一个结点,在遍历到一个结点之前我们已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度(某一结点的深度等于它到叶节点的路径的长度),我们就可以一边遍历一边判断每个结点是不是平衡的。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root,int *depth)
{
if(root == NULL)
{
*depth = 0;
return true;
}
int dright = 0 ;
int dleft = 0 ;
if(isBalanced(root->left,&dleft) && isBalanced(root->right,&dright))//从下至上的方式遍历
{
int diff = dleft - dright;
if(diff >= -1 && diff <= 1)
{
*depth = 1 + (dleft > dright ? dleft : dright);
return true;
}
}
return false;
}
bool isBalanced(TreeNode *root)
{
int depth = 0;//树高
return isBalanced(root,&depth);
}
};
参考:http://zhedahht.blog.163.com/blog/static/25411174201142733927831/