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

(015)实现一个函数来检查是否平衡树(keep it up)

时间:2015-07-25 21:24:39      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

实现一个函数来检查是否平衡树。这个问题而言。 平衡指的是这棵树随意两个叶子结点到根结点的距离之差不大于1。

这个题我们能够採用暴力搜索,找到叶子节点到根节点的最小值和最大值。然后他们的差假设大于1就不是平衡树,反之

则是平衡树。

int MinDepth = std::numeric_limits<int>::max();
int MaxDepth = std::numeric_limits<int>::min();

struct TreeNode
{
	int data;
	TreeNode* child;
	TreeNode* brother;
};

bool isBlanceTree(const TreeNode* vNode, int vDepth=0)
{
	if (vNode == NULL)
	{
		if (vDepth == 0) return true;

		if (vDepth < MinDepth) 
		{
			MinDepth = vDepth;
		}

		if (vDepth > MaxDepth)
		{
			MaxDepth = vDepth;
		}

		if (MaxDepth - MinDepth > 1) return false;
		return true;
	}

	bool IsBlance = true;
	if (vNode->child != NULL)
	{
		IsBlance = isBlanceTree(vNode->child, vDepth+1);
	}

	if (IsBlance && vNode->brother != NULL)
	{
		IsBlance = isBlanceTree(vNode->brother, vDepth);
	}

	return IsBlance;
}


版权声明:本文博客原创文章,博客,未经同意,不得转载。

(015)实现一个函数来检查是否平衡树(keep it up)

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4676470.html

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