/** * 题目描述 * 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍 * 历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}, * 则重建二叉树并返回。 */
从题目可以看出本题考点在于对二叉树几种遍历的理解
1.前序遍历 根-左-右
2.中序遍历 左-根-右
3.后序遍历 左-右-根
重建二叉树的关键在于找到根节点,然后组装左右子树
代码如下
public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
//判断参数合法性
if (pre.length == 0)
return null;
//如果只有一个节点,直接返回
if (pre.length == 1)
return new TreeNode(pre[0]);
//找到根节点位置,因为前序遍历第一个为根节点,中序遍历左边为左子树所以根节点问pre[0]
int rootIndex = 0;
for (int i = 0; i < in.length; i++) {
if (pre[0] == in[i]) {
rootIndex = i;
break;
}
}
TreeNode root = new TreeNode(pre[0]);
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, rootIndex + 1), Arrays.copyOfRange(in, 0, rootIndex));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, rootIndex + 1, pre.length), Arrays.copyOfRange(in, rootIndex + 1, in.length));
return root;
}
public static void main(String[] args) {
// 前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
final TreeNode treeNode = reConstructBinaryTree(pre, in);
}
难点在于递归的理解和二叉树遍历方式的理解,多做多练,熟练于心