zoukankan      html  css  js  c++  java
  • LeetCode 106. 从中序与后序遍历序列构造二叉树

    题目描述链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

    解题思路:其基本思路同题目:从前序与中序遍历序列构造二叉树 的基本思路一致,采用递归法,将大问题

    化为小问题。即得到左子树与右子树的序列的中序序列和后序序列继续递归的构造。

    其LeetCode C++ 求解代码如下:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        unordered_map<int,int>index;//获取其在中序序列中的位置
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            int len=inorder.size();
            for(int i=0;i<len;++i){
                index[inorder[i]]=i;
            }
    
            return myTree(inorder,postorder,0,len-1,0,len-1);
        }
      TreeNode* myTree(vector<int>& inorder ,vector<int>& postorder,int in_left,int in_right,int post_left,int post_right){
            if(post_left>post_right){
                return NULL;
            }
            int temp=postorder[post_right];
            TreeNode* root=new TreeNode(temp);
            int size=index[temp]-in_left;
            root->left=myTree(inorder,postorder,in_left,index[temp]-1,post_left,post_left+size-1);
            root->right=myTree(inorder,postorder,index[temp]+1,in_right,post_left+size,post_right-1);
            return root;
    
      }   
    
    
    };
  • 相关阅读:
    动手动脑3
    AWK编程与应用
    BASH内置变量的使用
    服务器交互脚本expect
    编程对话框的界面程序
    每日打卡
    AppiumLibrary中文翻译
    Bootstrap4简单使用
    Python基础06-类与对象
    BDD模式-Python behave的简单使用
  • 原文地址:https://www.cnblogs.com/zzw-/p/13498379.html
Copyright © 2011-2022 走看看