题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路
二叉树的前序遍历、中序遍历规则为:
- 前序遍历:根节点 -> 左子树 -> 右子树
- 中序遍历:左子树 -> 根节点 -> 右子树
因此,根据题目给出的前序序列和中序序列,结合二叉树遍历规则,通过如下步骤完成二叉树重建:
- 前序遍历的第一个节点为根节点,即root.val的值为pre[0]
- 遍历中序节点,找到值为pre[0]的位置,左边为左子树root.left,右边为右子树root.right
- 递归调用1、2步骤,完成二叉树重建。
功能实现采用数组下标移动方式实现,时间复杂度: ,空间复杂度:
实现代码
/**
* 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 TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || in.length == 0) {
return null ;
}
return constructRootNode(pre, 0, pre.length, in, 0, in.length) ;
}
public TreeNode constructRootNode(int[] pre, int pStart, int pEnd, int[] in, int iStart, int iEnd) {
if(pStart >= pEnd || iStart >= iEnd) {
return null ;
}
TreeNode root = new TreeNode(pre[pStart]) ;
for(int i=iStart; i<iEnd; i++) {
if(root.val == in[i]) {
int count = i - iStart ;
root.left = constructRootNode(pre, pStart+1, pStart+count+1, in, iStart, i) ;
root.right = constructRootNode(pre, pStart+count+1, pEnd, in, i+1, iEnd) ;
}
}
return root ;
}