题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
分析:
根据前序遍历可知第一位元素为根节点,接着遍历中序遍历序列,值与前序遍历序列的第一个值相等的即为根节点,记中序遍历中根节点的下标为pivot,则pivot左边的为左子树,右边的为右子树。则分别将根节点的左子树和右子树当成一颗完整的树,继续上述操作,递归求解。
C++代码:
/**
* 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* BT(vector<int> cpre, int b1, int e1, vector<int> cvin, int b2, int e2)
{
if(b1 > e1 || b2 > e2)
return NULL;
TreeNode* root = new TreeNode(cpre[b1]);
int pivot = b2;
while(pivot <= e2 && cvin[pivot] != cpre[b1])
{
pivot++;
}
root->left = BT(cpre, b1+1, b1+pivot-b2, cvin, b2, pivot-1);
root->right = BT(cpre, b1+pivot-b2+1, e1, cvin, pivot+1, e2);
return root;
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
return BT(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
}
};
Java代码:
public class Solution {
public TreeNode BT(int [] pre, int b1, int e1, int [] in, int b2, int e2)
{
if(b1 > e1 || b2 > e2)
return null;
TreeNode root = new TreeNode(pre[b1]);
int pivot = b2;
while(pivot <= e2 && in[pivot] != pre[b1])
pivot++;
root.left = BT(pre, b1+1, b1+pivot-b2, in, b2, pivot-1);
root.right = BT(pre, b1+pivot-b2+1, e1, in, pivot+1, e2);
return root;
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return BT(pre, 0, pre.length-1, in, 0, in.length-1);
}
}