albon arith

一些总结,欢迎交流

重建二叉树

根据中序遍历和前序遍历重建二叉树,同时验证是否合法。


#include <iostream>
#include <string>

using namespace std;

#define TREELEN 6

struct Node
{
	Node* pLeft;
	Node* pRight;
	char value;
};

Node* rebuild(char *preOrder, char *inOrder, int nTreeLen)
{
	Node *pTemp = new Node;
	pTemp->value = *preOrder;	
	pTemp->pLeft = NULL;
	pTemp->pRight = NULL;

	cout<<pTemp->value<<endl;

	int letter[26];
	for(int i=0; i<26; ++i)
	{
		letter[i] = 0;
	}
	// 验证前序遍历和中序遍历字符种类个数是否一致
	for(int i=0; i<nTreeLen; ++i)
	{
		char temp = *(preOrder+i);
		if(islower(temp))
		{
			letter[temp-'a']++;
		}
		else if(isupper(temp))
		{
			letter[temp-'A']++;
		}

		temp = *(inOrder+i);
		if(islower(temp))
		{
			letter[temp-'a']--;
		}
		else if(isupper(temp))
		{
			letter[temp-'A']--;
		}
	}
	for(int i=0; i<26; ++i)
	{
		if(letter[i] != 0)
		{
			cout<<"error string!"<<endl;
			throw runtime_error("error string!");
		}
	}



	if(nTreeLen == 1)
	{
		return pTemp;
	}

	// 求左右子树长度
	int leftTreeLen = 0;
	int rightTreeLen = 0;
	for(int i=0; i<nTreeLen; ++i)
	{
		if( *preOrder == *(inOrder+i) )
		{
			leftTreeLen = i;
			rightTreeLen = nTreeLen - i - 1;
			break;
		}
	}

	if(leftTreeLen > 0)
	{
		pTemp->pLeft = rebuild(preOrder+1, inOrder, leftTreeLen);
	}

	if(rightTreeLen > 0)
	{
		pTemp->pRight = rebuild(preOrder+leftTreeLen+1, inOrder+leftTreeLen+1, rightTreeLen);
	}

	return pTemp;

}

void traversal(Node* root, int flag)
{
	if(root == NULL)
		return;
	if(flag == 0)
	{
		cout<<root->value<<"\t";
		traversal(root->pLeft, flag);
		traversal(root->pRight, flag);
	}
	else if(flag == 1)
	{		
		traversal(root->pLeft, flag);
		cout<<root->value<<"\t";
		traversal(root->pRight, flag);
	}
}

int main()
{
	char preOrder[TREELEN] = {'a','b','d','c','e','f'};
	char inorder[TREELEN] = {'d','b','a','e','c','f'};

	Node* root = NULL;
	root = rebuild(preOrder, inorder, TREELEN);

	cout<<"\n前序遍历:"<<endl;
	traversal(root, 0);
	cout<<"\n中序遍历:"<<endl;
	traversal(root, 1);

}


阅读更多

扫码向博主提问

去开通我的Chat快问

hustspy1990

博客专家

顺其自然
  • 擅长领域:
  • Java
  • 性能优化
  • 系统设计
  • 高可用
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hustspy1990/article/details/8454357
上一篇算法题&lt;度度熊就是要刷排名第一&gt;
下一篇Ubuntu下安装Hadoop和配置Eclipse开发Hadoop
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭