/*
问题描述:平衡二叉树,给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
来源:LintCode
作者:syt
问题描述:平衡二叉树,给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
来源:LintCode
作者:syt
日期:2017-11-10
思路:计算每个结点的左子树和右子树的深度,并判断是否是平衡二叉树
*/
#include <iostream>
class TreeNode
{
public:
int val;
TreeNode *left, *right;
TreeNode(){}
TreeNode(int val, TreeNode *lptr = NULL, TreeNode *rptr = NULL) {
this->val = val;
this->left = lptr;
this->right = rptr;
}
};
#include "d_tree.h"
#include <queue>
using namespace std;
/*
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int calDepth(TreeNode* root)
{
if (root == NULL)
return 0;
int left = calDepth(root->left);
int right = calDepth(root->right);
int max = 0;
if (left > right)
max = left + 1;
else
max = right + 1;
return max;
}
bool isBalanced(TreeNode * root) {
// write your code here
if (root == NULL)
return true;
queue<TreeNode *> q;
TreeNode* p;
q.push(root);
while (!q.empty())
{
p = q.front();
q.pop();
int left = calDepth(p->left);
int right = calDepth(p->right);
int res = left - right;
if (res > 1 || res < -1)
return false;
if (p->left != NULL)
q.push(p->left);
if (p->right != NULL)
q.push(p->right);
}
return true;
}
TreeNode *buildTree()
{
TreeNode *root, *b, *c, *d, *e, *f, *g, *h;
h = new TreeNode(8);
g = new TreeNode(7);
f = new TreeNode(6);
e = new TreeNode(5);
d = new TreeNode(4, g, h);
c = new TreeNode(3, e, f);
b = new TreeNode(2, d, (TreeNode *)NULL);
root = new TreeNode(1, b, c);
return root;
}
void main()
{
TreeNode *root = buildTree();
cout << isBalanced(root) << endl;
}