Problem: 889. 根据前序和后序遍历构造二叉树
题目描述
思路
由于只根据前序和后序遍历无法唯一的构造构造一个二叉树,所以:
1.首先把前序遍历结果的第一个元素或者后序遍历结果的最后一个元素确定为根节点的值。
2.然后把前序遍历结果的第二个元素作为左子树的根节点的值。
3.在后序遍历结果中寻找左子树根节点的值,从而确定了左子树的索引边界,进而确定右子树的索引边界,递归构造左右子树即可。
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数
空间复杂度:
O ( h e i g h t ) O(height) O(height);其中 h e i g h t height height为二叉树的
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer, Integer> valToIndex = new HashMap<>();
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
for (int i = 0; i < postorder.length; ++i) {
valToIndex.put(postorder[i], i);
}
return build(preorder, 0, preorder.length - 1, postorder, 0, postorder.length - 1);
}
private TreeNode build(int[] preorder, int preStart, int preEnd, int[] postorder, int postStart, int postEnd) {
if (preStart > preEnd) {
return null;
}
if (preStart == preEnd) {
return new TreeNode(preorder[preStart]);
}
int rootVal = preorder[preStart];
int leftRootVal = preorder[preStart + 1];
int index = valToIndex.get(leftRootVal);
//左子树元素的个数(因为此时index是左子树的根节点的索引,所以要加上1)
int leftSize = index - postStart + 1;
TreeNode root = new TreeNode(rootVal);
root.left = build(preorder, preStart + 1, preStart + leftSize, postorder, postStart, index);
root.right = build(preorder, preStart + leftSize + 1, preEnd, postorder, index + 1, postEnd - 1);
return root;
}
}