题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路:
这道题首先要自己用笔在纸上能建立出来。
就用题目举例,前序第一个是1那根节点肯定是1,然后看中序遍历,4 7 2在1的左边,那4 7 2就在1的左子树,5 3 8 6就在右子树。
然后在看前序遍历2 4 7那子树的根结点就是2,中序4 7 2,左子树就是 4 7,右子树为空。
如此递归下去最终求得二叉树。
———-Python 2.7
# -*- 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
if 1 == len(pre):
return TreeNode(pre[0])
root = TreeNode(pre[0])
index = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:index + 1], tin[:index])
root.right = self.reConstructBinaryTree(pre[1 + index:], tin[index + 1:])
return root
———- C/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* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode* tree = new TreeNode(pre[0]);
//中序遍历数组
vector<int> lmid, rmid;
//前序遍历数组
vector<int> lpre, rpre;
for(int i = 0; i < vin.size(); i++){
//找到树或子树的根结点
if (pre[0] == vin[i]){
//根节点左侧中序数组
for(int j = 0; j < i; j++){
lmid.push_back(vin[j]);
}
//根节点右侧中序数组
for(int j = i + 1; j < vin.size(); j++){
rmid.push_back(vin[j]);
}
//从前序数组第二个起,复制子树结点个数个,到左子树前序数组 1 2 4 7 从2起复制三个也就是 i的值
for(int j = 1;j <= i; j++){
lpre.push_back(pre[j]);
}
//后面都是右子树的前序数组
for(int j = i + 1; j < vin.size(); j++){
rpre.push_back(pre[j]);
}
if(lpre.empty()){
tree->left = NULL;
}
else{
tree->left = reConstructBinaryTree(lpre, lmid);
}
if(rpre.empty()){
tree->right = NULL;
}
else{
tree->right = reConstructBinaryTree(rpre, rmid);
}
break;
}
}
return tree;
}
};