Leetcode: Construct Binary Tree from Inorder and Postorder Traversal

时间:2023-01-06 12:26:04
Given inorder and postorder traversal of a tree, construct the binary tree.

Construct Binary Tree from Inorder and Preorder Traversal问题非常类似,唯一区别在于这一次确定root的位置由post traversal来确定,为最后一个元素。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode buildTree(int[] inorder, int[] postorder) {
12         if (inorder.length==0 || postorder.length==0 || inorder.length!=postorder.length) {
13             return null;
14         }
15         int len = inorder.length;
16         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
17         for (int i=0; i<inorder.length; i++) {
18             map.put(inorder[i], i);
19         }
20         return helper(postorder, 0, len-1, inorder, 0, len-1, map);
21     }
22     
23     public TreeNode helper(int[] postorder, int posL, int posR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> map) {
24         if (posL>posR || inL>inR) {
25             return null;
26         }
27         TreeNode root = new TreeNode(postorder[posR]);
28         int index = map.get(postorder[posR]);
29         root.left = helper(postorder, posL, posL+index-1-inL, inorder, inL, index-1, map);
30         root.right = helper(postorder, posL+index-inL, posR-1, inorder, index+1, inR, map);
31         return root;
32     }
33 }