前序遍历和中序遍历树构造二叉树
Posted brucemengbm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前序遍历和中序遍历树构造二叉树相关的知识,希望对你有一定的参考价值。
例子
题目来自LintCode, 给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回例如以下的树:
2
/ 1 3
代码实现
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public:
int Get_root_index(vector<int> &preorder, vector<int> &inorder, int len)
{
int root_val = preorder[0];
for(int i = 0; i < len; i++)
{
if(inorder[i] == root_val)
return i;
}
return -1;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// write your code here
int pre_len = preorder.size();
int in_len = inorder.size();
if(pre_len <= 0 && in_len <= 0)
return NULL;
int RootValue = preorder[0];
TreeNode *root = new TreeNode();
root->val = RootValue;
if(pre_len == 1 && in_len == 1)
return root;
int index = Get_root_index(preorder, inorder, pre_len);
vector<int> left_Preorder, left_Inorder, right_Preorder, right_Inorder;
for(int i = 0; i < index; i ++)
{
left_Preorder.push_back(preorder[i+1]);
left_Inorder.push_back(inorder[i]);
}
for(int i = index + 1; i < pre_len; i ++)
{
right_Preorder.push_back(preorder[i]);
}
for(int i = index + 1; i < in_len; i ++)
{
right_Inorder.push_back(inorder[i]);
}
root->left = buildTree(left_Preorder, left_Inorder);
root->right = buildTree(right_Preorder, right_Inorder);
return root;
}
};
以上是关于前序遍历和中序遍历树构造二叉树的主要内容,如果未能解决你的问题,请参考以下文章