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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-03-09 14:29:02      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *CreatTree(vector<int>::iterator in_begin, vector<int>::iterator in_end, vector<int>::iterator pos_begin, vector<int>::iterator pos_end )
{
	if (in_begin == in_end)
		return NULL;

	vector<int>::iterator Rootpos = pos_end-1;
	vector<int>::iterator Rootino = find(in_begin, in_end, *Rootpos);
	auto lenleft = distance(in_begin, Rootino);
	TreeNode *root = new TreeNode(*Rootpos);
	root->left  = CreatTree(in_begin, Rootino, pos_begin, pos_begin + lenleft);
	root->right = CreatTree(Rootino + 1, in_end, pos_begin + lenleft, Rootpos);
	return root;

}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {

	if (inorder.empty())
		return NULL;
	TreeNode *Root = new TreeNode(0);
	Root = CreatTree(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
	return Root;
}


 

 

Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/44154209

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