设为首页 加入收藏

TOP

110.Balanced Binary Tree
2015-07-20 17:18:12 来源: 作者: 【 】 浏览:3
Tags:110.Balanced Binary Tree

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
  
   
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");
}

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[codevs 1789] 最大获利(2006年N.. 下一篇poj2112Optimal Milking(最优秀的..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何理解c语言指针和 (2025-12-27 01:19:11)
·为什么C标准库没有链 (2025-12-27 01:19:08)
·玩转C语言和数据结构 (2025-12-27 01:19:05)
·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)