您的位置:首页 > 其它

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal (用中序和后序树遍历来建立二叉树)

2017-08-27 09:18 615 查看

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 的位置关系递归

 

/**
* 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)
{
Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();

// save inorder number as key, position as value into map
for(int i=0; i<inorder.length; i++)
inMap.put(inorder[i], i);

TreeNode root = helper(postorder, postorder.length-1, 0, inorder.length - 1, inMap);

return root;
}

public TreeNode helper(int[] postorder, int postEnd, int inStart, int inEnd,
Map<Integer, Integer> inMap)
{
if(inStart > inEnd)
return null;

int rootVal = postorder[postEnd];
TreeNode root = new TreeNode(rootVal);
int inRoot = inMap.get(rootVal);  // position in inOrder

/* inStart & inEnd: for left child, move inEnd to the left of root
*                  for right child, move inStart to the right of root */
root.right = helper(postorder, postEnd - 1, inRoot + 1, inEnd, inMap);
/* postStart: for right left, go to inorder to check how many right children does root have,
* add it into postorder to skip them to reach left child */
root.left = helper(postorder, postEnd - (inEnd - inRoot) - 1, inStart, inRoot - 1, inMap);

return root;
}
}

参考资料:N/A

 

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐