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

Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-03-09 10:57:56      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

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>
#include<map>
#include<algorithm>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *CreatNode(vector<int>::iterator pre_begin, vector<int>::iterator pre_end, vector<int>::iterator ino_begin, vector<int>::iterator ino_end)
{
	if (pre_begin == pre_end)
		return NULL;
	TreeNode* curnode = new TreeNode(*pre_begin);
	auto iter = find(ino_begin, ino_end, *pre_begin);
	int lenLeftTree = distance(ino_begin, iter);
	curnode->left  = CreatNode( pre_begin + 1, pre_begin +1+ lenLeftTree, ino_begin, iter);
	curnode->right = CreatNode( pre_begin + 1+lenLeftTree, pre_end, iter+1,ino_end );

	return curnode;
}

TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
	
	if (preorder.empty())
		return NULL;

	TreeNode* root = new TreeNode(0);
	root = CreatNode(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
	return root;
}


 

Construct Binary Tree from Preorder and Inorder Traversal

标签:

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

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