码迷,mamicode.com
首页 > 其他好文 > 详细

110.Balanced Binary Tree

时间:2015-02-10 23:18:11      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binarytree in which the depth of the two subtrees of every nodenever differ by more than 1.

HideTags

 Tree Depth-first Search

 

 

#pragma once
#include<iostream>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

//取最大值
int max(int a, int b)
{
	if (a > b)
		return a;
	return b;
}

//求深度
int findDepth(TreeNode* p)
{
	if (!p)
		return 0;
	return max(findDepth(p->left), findDepth(p->right)) + 1;
}

//平衡条件:左平衡+右平衡+左右深度差小于等于1
bool isBalanced(TreeNode *root) 
{

	if (!root)//空节点也平衡
		return true;
	if (isBalanced(root->left) && isBalanced(root->right) && abs(findDepth(root->left) - findDepth(root->right)) <= 1)
		return true;
	return false;
}

void main()
{
	TreeNode* t1 = new TreeNode(1);
	TreeNode* t12 = new TreeNode(2);
	TreeNode* t22 = new TreeNode(2);
	TreeNode* t13 = new TreeNode(3);
	TreeNode* t23 = new TreeNode(3);
	TreeNode* t14 = new TreeNode(4);
	TreeNode* t24 = new TreeNode(4);

	t1->left = t12;
	t12->left = t13;
	t13->left = t14;
	t1->right = t22;
	t22->right = t23;
	t23->right = t24;

	cout << isBalanced(t1) << endl;
	cout << findDepth(t12) << endl;
	system("pause");
}

110.Balanced Binary Tree

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43707461

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!