题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路
前序遍历序列的第一个数字是根结点值;
中序遍历中根结点的左边序列是左子树,右边序列是右子树。
C++代码实现
C++ clang++3.9
运行错误:请检查是否存在数组、列表等越界非法访问,内存非法访问等情况
不知道哪儿错了,先保存,回头再来看
/**
* 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* R(vector <int>a,int astart,int aend,vector<int> b,int bstart,int bend){
if (astart>=aend||bstart>=bend)
return NULL;
TreeNode* root=new TreeNode(a[astart]);
int i;
for (i=bstart;i<bend;i++)
if(a[astart]==b[i])
break;
root->left=R(a,astart+1,astart+i-bstart,b,bstart,i-1);
root->right=R(a,astart+i-bstart+1,aend,b,i+1,bend);
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
return R(pre,0,pre.size(),vin,0,vin.size());
}
};
python实现
python 2.7.3
pop(0)是神来之笔
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root=TreeNode(pre.pop(0))
index=tin.index(root.val)
root.left=self.reConstructBinaryTree(pre,tin[:index])
root.right=self.reConstructBinaryTree(pre,tin[index+1:])
return root