【在线编程】重建二叉树
【问题描述】
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
【解题思路 & Java实现】
思路:分治法。因为前序遍历是 “根左右”,中序遍历是 “左根右”。所以从pre中第一个元素得到根root,然后在in中找到root的位置index,将 in 分为两部分,index左边为左子树,index右边为右子树。分别对左边和右边进行递归建树。
注意:
- 递归出口
- 递归时数组的下标如何确定?(根据“前序遍历和中序遍历的结点个数一定是相同的”来简单计算即可)
代码1: 借用 Arrays.copyOfRange(array, from. , to) 左闭右开
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
int index = 0;
while (index < in.length && in[index] != root.val) {
index++;
}
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, index + 1, pre.length), Arrays.copyOfRange(in, index + 1, in.length));
return root;
}
}
代码二:函数中传入下标来截取数组。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
return reConstructBinaryTreeHandler(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
public static TreeNode reConstructBinaryTreeHandler(int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight) {
//递归出口
if (preLeft > preRight || inLeft > inRight) {
return null;
}
TreeNode root = new TreeNode(pre[preLeft]);
int index = 0;
while (index < inRight && in[index] != root.val) {
index++;
}
root.left = reConstructBinaryTreeHandler(pre, preLeft + 1, index - inLeft + preLeft, in, inLeft, index - 1);
root.right = reConstructBinaryTreeHandler(pre, index - inLeft + preLeft + 1, preRight, in, index + 1, inRight);
return root;
}
}