给定两个整数数组,preorder 和 postorder ,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。
如果存在多个答案,您可以返回其中 任何 一个。
class Solution {
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
int n = preorder.length;
Map<Integer, Integer> postMap = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
postMap.put(postorder[i], i);
}
return dfs(preorder, postorder, postMap, 0, n - 1, 0, n - 1);
}
public TreeNode dfs(int[] preorder, int[] postorder, Map<Integer, Integer> postMap, int preLeft, int preRight, int postLeft, int postRight) {
if (preLeft > preRight) {
return null;
}
int leftCount = 0;
if (preLeft < preRight) {
leftCount = postMap.get(preorder[preLeft + 1]) - postLeft + 1;
}
return new TreeNode(preorder[preLeft],
dfs(preorder, postorder, postMap, preLeft + 1, preLeft + leftCount, postLeft, postLeft + leftCount - 1),
dfs(preorder, postorder, postMap, preLeft + leftCount + 1, preRight, postLeft + leftCount, postRight - 1));
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-postorder-traversal/solutions/2645281/gen-ju-qian-xu-he-hou-xu-bian-li-gou-zao-6vzt/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:preorder,postMap,leftCount,int,前序,二叉树,preLeft,889,postorder
From: https://www.cnblogs.com/tianyiya/p/18099633