给定两个整数数组,preorder 和 postorder ,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。
如果存在多个答案,您可以返回其中 任何 一个。
图1 根据前序遍历和后续遍历构造二叉树
示例 1:
输入:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解、递归解法,首先根据前序遍历的第一个节点是当前树的根节点,后一个节点为左子树的根节点,然后在后序遍历中进行索引查找,找到对应值的索引+1即为左子树的节点个数,创建前序遍历左子树的数组、前序遍历右子树的数组、后序遍历左子树的数组、后序遍历右子树的数组,进行节点递归生成。
class Solution {
public TreeNode constructFromPrePost(int[] pre, int[] post) {
if (pre == null || pre.length == 0) return null;
return dfs(pre, post);
}
public TreeNode dfs(int[] pre, int[] post) {
if (pre == null || pre.length == 0) return null;
int n = pre.length;
if (n == 1) return new TreeNode(pre[0]);
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < post.length; i++) {
if (pre[1] == post[i]) {
int leftCount = i + 1;
int[] pre_left = Arrays.copyOfRange(pre, 1, leftCount + 1);
int[] pre_right = Arrays.copyOfRange(pre, leftCount + 1, n);
int[] post_left = Arrays.copyOfRange(post, 0, leftCount);
int[] post_right = Arrays.copyOfRange(post, leftCount, n -1);
root.left = dfs(pre_left, post_left);
root.right = dfs(pre_right, post_right);
break;
}
}
return root;
}
}