• 106. Construct Binary Tree from Inorder and Postorder Traversal


    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder==null || postorder==null || inorder.length==0 || postorder.length==0)
        {
            return null;
        }
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0;i<inorder.length;i++)
        {
            map.put(inorder[i],i);
        }
        return helper(inorder,postorder,0,inorder.length-1, 0, postorder.length-1,map);
    }
    private TreeNode helper(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR,
    HashMap<Integer, Integer> map) { if(inL>inR || postL>postR) //构造树的递归出口, return null; TreeNode root = new TreeNode(postorder[postR]); int index = map.get(root.val); root.left = helper(inorder,postorder,inL,index-1,postL,postL+index-inL-1,map); root.right = helper(inorder,postorder,index+1,inR, postL+index-inL, postR-1,map); return root; }

    做个test case 看看起始点和终止点的位置, 构造树都不包括遍历过得 

  • 相关阅读:
    三元运算
    sys and os
    print.format
    while loop
    线段树模板
    Round #431 (Div.2)
    D. Make a Permutation!
    Round #411 (Div.2)
    Round #432 (Div.2)
    Round #433 (Div.2)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7270484.html
Copyright © 2020-2023  润新知