首页 > 代码库 > 前序遍历和中序遍历树构造二叉树
前序遍历和中序遍历树构造二叉树
例子
题目来自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 = http://www.mamicode.com/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;
}
};
前序遍历和中序遍历树构造二叉树
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。