程序员面试题精选100题(60)-判断二叉树是不是平衡

// 程序员面试题精选100题(60)-判断二叉树是不是平衡.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

struct TNode{
	char chValue;
	TNode *leftChild;
	TNode *rightChild;
};
TNode* rebuildTree(char *preOrder,int start1,char *midOrder,int start2,int n)//根据前序和中序建立二叉树 长度为N
{
	TNode *root;
	if(n==0) return NULL;
	root = new TNode;
	int pivet;
	char chroot;
	chroot=preOrder[start1];
	root->chValue = chroot;
	for(int i=start2;i<start2+n;i++)//include start1 
	{
		if(midOrder[i]==chroot) { pivet = i;break;}
	}
	if(pivet-start2>0)
		root->leftChild=rebuildTree(preOrder,start1+1,midOrder,start2,pivet-start2);
	else root->leftChild = NULL;
	if(n-pivet+start2-1>0)//pivet-start2 is the half number,
		root->rightChild=rebuildTree(preOrder,start1+1+pivet-start2,midOrder,pivet+1,n-pivet+start2-1);
	else root->rightChild = NULL;
	return root;
}
void preprint(TNode *root)
{
	if(root!=NULL)
	{
		cout<<root->chValue<<" ";
		preprint(root->leftChild);
		preprint(root->rightChild);
	}
}
int flag=1;
int isbalance(TNode *root)
{
	if (flag==0)
	{
		return -1;
	}
	if (root==NULL)
	{
		return 0;
	}
	int h1=isbalance(root->leftChild)+1;
	int h2=isbalance(root->rightChild)+1;
	if (abs(h1-h2)>1)
	{
		flag=0;
	}
	return h1>h2?h1:h2;
}
//
bool IsBalanced(TNode* pRoot, int* pDepth)
{
	if(pRoot == NULL)
	{
		*pDepth = 0;
		return true;
	}

	int left, right;
	if(IsBalanced(pRoot->leftChild, &left)
		&& IsBalanced(pRoot->rightChild, &right))
	{
		int diff = left - right;
		if(diff <= 1 && diff >= -1)
		{
			*pDepth = 1 + (left > right ? left : right);
			return true;
		}
	}

	return false;
}
bool IsBalanced(TNode* pRoot)
{
	int depth = 0;
	return IsBalanced(pRoot, &depth);
}

int _tmain(int argc, _TCHAR* argv[])
{
	TNode* rootparent,*rootchild;
	int n,m;
	cout<<"input n"<<endl;
	cin>>n;
	char *preOrder=new char[n];
	char *midOrder=new char[n];
	cout<<"input preorder1"<<endl;
	for(int i=0;i<n;i++)
		cin>>preOrder[i];
	cout<<"input midorder1"<<endl;
	for(int i=0;i<n;i++)
		cin>>midOrder[i];
	rootparent=rebuildTree(preOrder,0,midOrder,0,n);
	preprint(rootparent);
	cout<<endl;
	isbalance(rootparent);
	if (flag==1)
	{
		cout<<"is balance "<<endl;
	}
	else
	{
		cout<<"is not balance "<<endl;
	}
	cout<<IsBalanced(rootparent);
	system("pause");
	return 0;
}
自己的程序好像不是很规范,或说不专业
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值