• 【算法编程 C++ Python】根据前序遍历、中序遍历重建二叉树


    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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
     
     
  • 相关阅读:
    ArrayList和Vector的区别?HashMap和Hashtable的区别?
    试题:关键字public, private, protected的区别?以及不写时默认是什么?
    试题:用JavaScript实现密码验证功能
    RPC和RMI的区别(Difference Between RPC and RMI)
    js中从blob提取二进制
    netty 3.9.2 UDP协议服务器和客户端DEMO
    Java NIO的多路复用及reactor
    android屏蔽home键的实现
    搜索引擎对相似图片搜索识别的原理(一)
    代理模式(设计模式)
  • 原文地址:https://www.cnblogs.com/xiangfeidemengzhu/p/9007114.html
Copyright © 2020-2023  润新知