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.
Hide Tags: Tree ,Depth-first Search
题目:判断一颗二叉树是否为平衡二叉树
思路:此题是Maximum Depth of Binary Tree 题目的延伸题目,递归判断每个节点的左右子树的最大深度是否只相差1。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if(root == NULL) return 0;
if(root->left == NULL && root->right == NULL) return 1;
else if(root->left == NULL) return maxDepth(root->right) + 1;
else if(root->right== NULL) return maxDepth(root->left ) + 1;
int l = maxDepth(root->left) + 1;
int r = maxDepth(root->right)+ 1;
return l>r?l:r;
}
bool isBalanced(struct TreeNode* root) {
if(root == NULL)
return true;//递归终止条件
if (abs(maxDepth(root->left) - maxDepth(root->right)) >1)
return false;//左右子树最大深度是否相差1
return isBalanced(root->left) && isBalanced(root->right);//递归查找每个节点的左右子树最大深度
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
[Leetcode]-Balanced Binary Tree
原文地址:http://blog.csdn.net/xiabodan/article/details/46771309