描述
Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre
and post
are distinct positive integers.
Example 1:
1 | Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] |
Note:
1 <= pre.length == post.length <= 30
pre[]
andpost[]
are both permutations of1, 2, ..., pre.length
.- It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.
分析
先序遍历和中序遍历,中序遍历和后序遍历这两个组合可以确定原二叉树,这是一个常用到的知识点。
pre 数组的第一个元素和 post 的最后一个元素是根节点,可以遍历 pre,依次作为根节点,同时确定 pre 后面的节点在 post 数组中的位置,该位置左边为 pre 后面的节点的子树,右边是根节点的子树,因此可以使用递归,位置关系可以用 HashMap 进行存储。
解决方案1(Java)
1 | /** |