Title Description
And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.
Time limit: C / C ++ 1 second, 2 seconds languages other
space restrictions: C / C ++ 32M, 64M other languages
code
This question is a common operation in the binary tree, the key is found in the preamble, the order of the characteristics of the function of problem-solving ideas, you can easily find the need to achieve a recursion.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
int lenth=pre.size();//记录数组长度
int mid=0;//记录递归过程的中间节点
vector<int> pre_left,pre_right,vin_left,vin_right;//记录递归过程中数组的左右子数组
//递归出口
if (lenth==0)
return NULL;
//创建根节点
TreeNode *head=new TreeNode(pre[0]);
//在中序数组找根节点
for(int i=0;i<lenth;i++)
{
if(vin[i]==pre[0])
{
mid=i;
break;
}
}
//前序第一个节点为根节点,对应中序中的第mid个节点
//中序数组pre中,mid左边的数作为左子树节点中序集合,右边的数作为右子树节点中序集合
//谦虚数组vin中,第2到(1+mid)的数作为左子树节点先序集合,剩余的数作为右子树节点先序集合
for(int i=0;i<mid;i++)
{
vin_left.push_back(vin[i]);
pre_left.push_back(pre[i+1]);
}
for(int i=mid+1;i<lenth;i++)
{
vin_right.push_back(vin[i]);
pre_right.push_back(pre[i]);
}
//递归,递归构建左、右子树,直到叶节点
head->left=reConstructBinaryTree(pre_left,vin_left);
head->right=reConstructBinaryTree(pre_right,vin_right);
return head;
}
};