描述
给定某二叉树的前序遍历和中序遍历,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
提示:
1.0 <= pre.length <= 2000
2.vin.length == pre.length
3.-10000 <= pre[i], vin[i] <= 10000
4.pre 和 vin 均无重复元素
5.vin出现的元素均出现在 pre里
6.只需要返回根结点,系统会自动输出整颗树做答案对比
示例1
输入: [1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]
返回值:{1,2,3,4,#,5,6,#,7,#,#,8}
说明: 返回根节点,系统会输出整颗二叉树对比结果
示例2
输入: [1],[1]
返回值: {1}
示例3
输入: [1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值: {1,2,5,3,4,6,7}
思路:
前序遍历和中序遍历,重建二叉树,主要应用dfs与递归
- 前序遍历的首元素就是当前递归层次的根节点
- 确定左右子树的范围,从中间向两边查找跟节点索引,从中序遍历中根据根节点的值找到中序遍历数组中根节点的索引
- 当前根节点的左子节点为左子树的跟节点,拼接、构建二叉树即可
时间复杂度 O(N):递归了每个结点,N为结点数
空间复杂度 O(N):递归所用的栈空间
代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre == null || pre.length == 0
|| in == null || in.length == 0
|| pre.length != in.length) {
return null;
}
return buildBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
}
private TreeNode buildBinaryTree(int [] pre, int beginPre, int endPre,
int [] in, int beginIn, int endIn) {
if (beginPre > endPre || beginIn > endIn) {
return null;
}
int val = pre[beginPre];
int rootValIn = beginIn;
while (rootValIn <= endIn) {
if (in[rootValIn] == val) {
break;
}
rootValIn++;
}
TreeNode root = new TreeNode(val);
//左子树长度
int leftLength = rootValIn - beginIn;
//右子树长度
int rightLength = endIn - rootValIn;
root.left = buildBinaryTree(pre, beginPre+1, beginPre + leftLength,
in, beginIn, rootValIn-1);
root.right = buildBinaryTree(pre, endPre - rightLength + 1, endPre,
in, rootValIn+1, endIn);
return root;
}
}