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

Construct binary tree from preorder and inoder--LeetCode

时间:2015-03-30 11:26:36      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   c++   

题目:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路:根据前序和中序的特点 递归调用创建二叉树

#include <iostream>
#include <vector>
using namespace std;

/**
由一个树的前序和中序列来构造树 
*/

typedef struct tree_node Tree;
struct tree_node
{
	Tree* left;
	Tree* right;
	int value;
}; 

Tree* helper(vector<int>& pre,int pre_begin,int pre_end,vector<int>& inorder,int in_begin,int in_end)
{
	Tree* root=NULL;
	int mid;
	int i; 
	if(pre_end -pre_begin < 0)
	{
		return NULL;
	}
	else
	{
	
		for(i=in_begin;i<=in_end;i++)
			if(inorder[i] == pre[pre_begin])
				break;
		if(i>in_end)
			return NULL;
			
		root = new Tree;

		root->value = pre[pre_begin];
		root->left = helper(pre,pre_begin+1,pre_begin+1+i-1-in_begin,inorder,in_begin,i-1);
		root->right = helper(pre,pre_begin+1+i-1-in_begin+1,pre_end,inorder,i+1,in_end);
		return root;
	}
}

Tree* createBintree(vector<int>& pre,vector<int>& inorder)
{
	if(pre.size()==0 || inorder.size()==0)
		return NULL;
	return helper(pre,0,pre.size()-1,inorder,0,inorder.size()-1);
}

/*前序遍历*/ 
void print_pre(Tree* tree)
{
	if(tree != NULL)
	{
		cout<<tree->value<<" "<<endl;
		print_pre(tree->left);
		print_pre(tree->right);
	}
}

/*中序遍历*/
void print_inorder(Tree* tree)
{
	if(tree != NULL)
	{
		print_inorder(tree->left);
		cout<<tree->value<<endl;
		print_inorder(tree->right);
	}
}

void print_post(Tree* root)
{
	if(root != NULL)
	{
		print_post(root->left);
		print_post(root->right);
		cout<<root->value<<endl;
	}
	
}



 
int main()
{
	int array[]={1,2,3,4,5,6,7,8};
	vector<int> inorder(array,array+sizeof(array)/sizeof(int));
	int array1[] ={4,2,1,3,7,6,5,8};
	
	vector<int> preorder(array1,array1+sizeof(array1)/sizeof(int));
	
	int array2[]={1,3,2,5,6,8,7,4};
	vector<int> postorder(array2,array2+sizeof(array2)/sizeof(int));
	
	
	Tree* root = createBintree(preorder,inorder);
	print_inorder(root);
	cout<<"============="<<endl;
	print_pre(root); 
	cout<<endl;
	cout<<"============="<<endl;
	
	//Tree* second = createBinTree(inorder,postorder);
	print_post(second);
	
	
	return 0;
}


Construct binary tree from preorder and inoder--LeetCode

标签:leetcode   算法   c++   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44746867

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