题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。(题目来源:牛客网剑指offer)
 
C++:5ms 504k
#include <vector>
#include <iostream>
using namespace std;

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) {
        m_pre = pre;
        m_vin = vin;
        return reConstructBinaryTree_part(0,pre.size()-1,0,vin.size()-1);
    }
private:
    vector<int> m_pre;
    vector<int> m_vin;
    TreeNode* reConstructBinaryTree_part(int pre_start, int pre_end, int vin_start, int vin_end){
        if (pre_start>pre_end || (vin_start>vin_end)){
            return NULL;}
        TreeNode* root = new TreeNode(m_pre[pre_start]);
        for(int i=vin_start; i<=vin_end; i++){
            if (m_vin[i]==root->val){
                root->left = reConstructBinaryTree_part(pre_start+1,pre_end,vin_start,i-1);
                root->right = reConstructBinaryTree_part(i-vin_start+pre_start+1,pre_end,i+1,vin_end);
                break;
            }
            else{
                continue;}
        }
        return root;
    }
};

void PreOrder(TreeNode* T){
    //output
    if(T){
        cout<<T->val<<" ";
        PreOrder(T->left);
        PreOrder(T->right);
    }
}

int main()
{
    Solution obj;
    vector<int> pre={1,2,4,7,3,5,6,8};
    vector<int> vin={4,7,2,1,5,3,8,6};
    TreeNode* root= obj.reConstructBinaryTree(pre, vin);
    PreOrder(root);//output
}

Python:65ms 6140k

# -*- 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[0])
        index = tin.index(pre.pop(0))
        # 注意:python index范围是左闭右开
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index+1:])
        return root

 

 
 
posted on 2018-05-08 11:07  想飞的萌猪  阅读(252)  评论(0编辑  收藏  举报