zoukankan      html  css  js  c++  java
  • 【算法编程 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
     
     
  • 相关阅读:
    Python中*和**的区别
    Python中str、list、numpy分片操作
    Python中bisect的使用方法
    Python中__str__和__repr__的区别
    Python中函数参数类型和参数绑定
    C++中explicit
    C++中const
    自动识别 URL
    .net中activex的替代技术:winform control(一)
    vs2005包加载有误的解决方法
  • 原文地址:https://www.cnblogs.com/xiangfeidemengzhu/p/9007114.html
Copyright © 2011-2022 走看看