标签:
题目:
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 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 == NULL)
return true;
if((root -> left == NULL ) && (root -> right == NULL))
return true;
int leftDepth = 0;
int rightDepth = 0;
return isSubBalance(root -> left,leftDepth) && isSubBalance(root -> right , rightDepth) && (abs(leftDepth - rightDepth) <= 1) ;
}
bool isSubBalance(TreeNode *root,int &depth)
{
if(root == NULL)
{
depth = 0;
return true;
}
if((root -> left == NULL ) && (root -> right == NULL))
{
depth = 1;
return true;
}
else
{
depth = 1;
int leftDepth = 0;
int rightDepth = 0;
return isSubBalance(root -> left,leftDepth) && isSubBalance(root -> right , rightDepth) && (abs(leftDepth - rightDepth) <= 1) && (depth += max(leftDepth,rightDepth) ) ;
}
}
};
Leetcode题目:Balanced Binary Tree
标签:
原文地址:http://www.cnblogs.com/CodingGirl121/p/5425720.html