想在牛客网上写此题目,请点击此处
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
分析:
前序遍历:根节点 -> 左子树 -> 右子树
中序遍历:左子树 -> 根节点 -> 右子树
后序遍历:左子树 -> 右子树 -> 根节点
当我们知道了前序遍历和中序遍历之后,我们可通过其遍历规则,将二叉树重建:
- 确定树的根节点:前序遍历的第一个结点就是二叉树的根节点
- 求解树的左右子树:找到根节点在中序遍历中的位置,根节点左边是二叉树的左子树,根节点的右边时二叉树的右子树;如果根节点的左边或右边为空,那么方向的子树为空;如果根节点的左边和右边都为空,那么该节点时叶子节点。
- 对左右子树分别进行1,2两个步骤,直至求出完整的二叉树结构为止。
代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
前序遍历:根结点 -> 左子树 -> 右子树
中序遍历:左子树 -> 根节点 -> 右子树
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
// pre:1 2 4 7 3 5 6 8
// in :4 7 2 1 5 3 8 6
TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
return root;
}
public TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn){
if(startPre > endPre || startIn > endIn){
return null;
}
// 根据前序遍历结果,创建根节点
TreeNode root = new TreeNode(pre[startPre]);
// 根节点为:1
// 在中序遍历的结果中找到根节点,找到其左右结点
// 中序结果分离: 对应的前序遍历
// 左子树:4 7 2 2 3 7
// 右子树:5 3 8 6 3 5 6 8
for(int i = startIn; i <= endIn; i++){
if(in[i] == pre[startPre]){
root.left = reConstructBinaryTree(pre, startPre+1, startPre+i-startIn, in, startIn, i-1);
root.right = reConstructBinaryTree(pre, i-startIn+startPre+1, endPre, in, i+1, endIn);
}
}
return root;
}
}
牛客网在线OJ执行结果为: