給定兩個整數陣列,preorder 和 postorder ,其中 preorder 是一個具有 無重複 值的二叉樹的前序遍歷,postorder 是同一棵樹的後序遍歷,重構並返回二叉樹。
如果存在多個答案,您可以返回其中 任何 一個。
https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-postorder-traversal/description/
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)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。