LeetCode 106. 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.

 


题目标签:Array, Tree

  这到题目和105 几乎是一摸一样的,唯一的区别就是把pre-order 换成 post-order。因为post-order是最后一个数字是root,所以要从右向左的遍历。还需要把helper function 里的 right child 和 left child 顺序更换一下,并且要把相关的代入值也改一下。具体可以看code。

 

 

Java Solution:

Runtime beats 68.55% 

完成日期:08/26/2017

关键词:Array, Tree

关键点:递归;利用post-order 和 in-order 的位置关系递归

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution 
11 {
12     public TreeNode buildTree(int[] inorder, int[] postorder) 
13     {
14         Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
15         
16         // save inorder number as key, position as value into map
17         for(int i=0; i<inorder.length; i++)
18             inMap.put(inorder[i], i);
19         
20         
21         TreeNode root = helper(postorder, postorder.length-1, 0, inorder.length - 1, inMap);
22         
23         return root;    
24     }
25     
26     public TreeNode helper(int[] postorder, int postEnd, int inStart, int inEnd, 
27             Map<Integer, Integer> inMap)
28     {
29         if(inStart > inEnd)
30             return null;
31         
32         int rootVal = postorder[postEnd];
33         TreeNode root = new TreeNode(rootVal);
34         int inRoot = inMap.get(rootVal);  // position in inOrder
35         
36         /* inStart & inEnd: for left child, move inEnd to the left of root
37          *                  for right child, move inStart to the right of root */
38         root.right = helper(postorder, postEnd - 1, inRoot + 1, inEnd, inMap);
39         /* postStart: for right left, go to inorder to check how many right children does root have,  
40          * add it into postorder to skip them to reach left child */
41         root.left = helper(postorder, postEnd - (inEnd - inRoot) - 1, inStart, inRoot - 1, inMap);
42         
43         return root;
44     }
45 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-08-27 09:18  Jimmy_Cheng  阅读(260)  评论(0编辑  收藏  举报