Construct Binary Tree from Traversals

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

  3
 / \
9  20
  /  \
 15   7

Note

找到subproblem,通过size来定位root,index就是inOrder中和root值相等的位置

在help function需要

int preStart, int inStart, int inEnd

Left

Right

preStart

preStart + 1

preStart + (index - inStart) + 1

inStart

inStart

index - inStart + 1

inEnd

index - 1

inEnd

这样我们就划分了不同的左右子问题

Code

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

Return the following binary tree:

Note

类似之前的找法,不过这次我们需要从后面往前找 (inEnd should not larger than inStart)

Left

Right

postStart

postStart - (inStart - Index) - 1

postStart - 1

inStart

index - 1

inStart

inEnd

inEnd

index + 1

Code

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals preandpost are distinct positive integers.

Example 1:

  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

  • permutations of length, from 1 to pre.length

Note

利用permutation这个条件,存post的位置,找preOrder根后面的第一个元素的位置,分别对划分左右

int N = map.get(pre[preStart + 1]) - postStart; ---- N is the length of Left subtree

Left

Right

preStart

preStart + 1

preStart + 1 + N + 1

preEnd

preStart + 1 + N

preEnd

postStart

postStart

postStart + N + 1

postEnd

postStart + N

postEnd - 1

Code

Last updated