從中序與後序遍歷序列構造二叉樹

lp151397發表於2020-09-25
中序遍歷 inorder = [9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int post_idx;
    int[] postorder;
    int []inorder;
    Map<Integer,Integer> idx_map = new HashMap<Integer,Integer>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.postorder=postorder;
        this.inorder=inorder;
        post_idx=postorder.length-1;
        int idx = 0;
        for(Integer val:inorder){
            idx_map.put(val,idx++);
        }
        return helper(0,inorder.length-1);
    }
    public TreeNode helper(int in_left,int in_right){
        if(in_left>in_right){
            return null;
        }
        int root_val=postorder[post_idx];
        TreeNode root = new TreeNode(root_val);
        int index = idx_map.get(root_val);
        post_idx--;
        root.right= helper(index+1,in_right);
        root.left = helper(in_left,index-1);
        return root;
    }

}

相關文章