题目:
给定两个整数数组,preorder 和 postorder ,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。
如果存在多个答案,您可以返回其中 任何 一个。
示例 1:
输入:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
示例 2:
输入: preorder = [1], postorder = [1]
输出: [1]
提示:
1 <= preorder.length <= 30
1 <= preorder[i] <= preorder.length
preorder 中所有值都 不同
postorder.length == preorder.length
1 <= postorder[i] <= postorder.length
postorder 中所有值都 不同
保证 preorder 和 postorder 是同一棵二叉树的前序遍历和后序遍历
java代码:
/**
* 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 {
public TreeNode constructFromPrePost(int[] pre, int[] post) {
int n = pre.length;
if (n == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
if (n == 1) {
return root;
}
int l = 0;
for (int i = 0; i < n; i++) {
if (post[i] == pre[1]) {
l = i + 1;
break;
}
}
int[] leftPre = new int[l];
int[] leftPost = new int[l];
int[] rightPre = new int[n - l - 1];
int[] rightPost = new int[n - l - 1];
for (int i = 1; i <= l; i++) {
leftPre[i - 1] = pre[i];
}
for (int i = 0; i < l; i++) {
leftPost[i] = post[i];
}
for (int i = l + 1; i < n; i++) {
rightPre[i - l - 1] = pre[i];
}
for (int i = l; i < n - 1; i++) {
rightPost[i - l] = post[i];
}
root.left = constructFromPrePost(leftPre, leftPost);
root.right = constructFromPrePost(rightPre, rightPost);
return root;
}
}
网友评论