zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    For example, given

    inorder = [9,3,15,20,7]
    postorder = [9,15,7,20,3]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7

    Approach #1: 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:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            int len = inorder.size();
            unordered_map<int, int> mp;
            for (int i = 0; i < len; ++i)
                mp[inorder[i]] = i;
            return solve(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1, mp);
        }
        
    private:
        TreeNode* solve(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe, unordered_map<int, int> mp) {
            if (is > ie || ps > pe) return NULL;
            TreeNode* root = new TreeNode(postorder[pe]);
            int it = mp[postorder[pe]];
            TreeNode* leftchild = solve(inorder, is, it-1, postorder, ps, ps+it-is-1, mp);
            TreeNode* rightchild = solve(inorder, it+1, ie, postorder, ps+it-is, pe-1, mp);
            root->left = leftchild;
            root->right = rightchild;
            return root;
        }
    };
    

      

    Approach #2: Java.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if (inorder == null || postorder == null || inorder.length != postorder.length) return null;
            HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
            for (int i = 0; i < inorder.length; ++i) {
                hm.put(inorder[i], i);
            }
            return buildTreePostIn(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hm);
        }
        
        private TreeNode buildTreePostIn(int[] inorder, int is, int ie, int[] postorder, int ps, int pe, HashMap<Integer, Integer> hm) {
            if (ps > pe || is > ie) return null;
            TreeNode root = new TreeNode(postorder[pe]);
            int ri = hm.get(postorder[pe]);
            TreeNode leftchild = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm);
            TreeNode rightchild = buildTreePostIn(inorder, ri+1, ie, postorder, ps+ri-is, pe-1, hm);
            root.left = leftchild;
            root.right = rightchild;
            return root;
        }
    }
    

      

    Approach #3: Python.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def buildTree(self, inorder, postorder):
            """
            :type inorder: List[int]
            :type postorder: List[int]
            :rtype: TreeNode
            """
            def helper(istart, iend, pstart, pend):
                if istart > iend or pstart > pend: return None
                root = TreeNode(postorder[pend])
                cur = idx[postorder[pend]]
                leftchild = helper(istart, cur-1, pstart, pstart+cur-istart-1)
                rightchild = helper(cur+1, iend, pstart+cur-istart, pend-1)
                root.left = leftchild
                root.right = rightchild
                return root
                
            idx = {}
            for i in range(len(inorder)):
                idx[inorder[i]] = i
            return helper(0, len(inorder)-1, 0, len(postorder)-1)
        
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    laravel passport 全局捕获 401 ,返回数据给前台
    服务器上每次执行git pull,都提示输入用户名和密码
    jQuery-File-Upload 使用,jQuery-File-Upload上传插件
    Java返回结果封装,SpringBoot返回结果封装
    Java Spring文件上传,Java文件上传,Java通用文件上传
    Mdb文件工具类,UCanAccess使用,Access数据库操作
    Access MDB文件解析查询,Access数据库解析工具类MdbUtils
    jquery easyui combogrid Uncaught TypeError:Cannot read property
    soap调用Jar包冲突,SOAPMessageContext
    js打开新窗口,js打开居中窗口,js打开自定义窗口
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10002713.html
Copyright © 2011-2022 走看看