问题描述
返回与给定的前序和后序遍历匹配的任何二叉树。
pre 和 post 遍历中的值是不同的正整数。
示例:
输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
提示:
1 <= pre.length == post.length <= 30
pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal
解答
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //树的前序遍历和后序遍历不能确定唯一的树。 class Solution { Map<Integer, Integer> idx; int[] post; int rootIdx; public TreeNode builder(int left, int right){ if(left>right)return null; int rootVal = post[rootIdx]; TreeNode root = new TreeNode(rootVal); rootIdx--; if(left==right)return root; if(rootIdx>=0){ int start = idx.get(post[rootIdx]); root.right = builder(start, right); root.left = builder(left+1, start-1); } return root; } public TreeNode constructFromPrePost(int[] pre, int[] post) { this.post = post; idx = new HashMap<Integer, Integer>(); for(int i=0;i<pre.length;i++)idx.put(pre[i], i); rootIdx = post.length-1; return builder(0, post.length-1); } }