注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:先序的第一个是根节点,根据根节点在中序中的位置将中序划分成左右子树,再递归实现,直到只剩一个结点再递归就会使得其左右子节点都为null并逐层返回。
/**
* 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) {
return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
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]);
for (int i = 0; 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, endPre - endIn + i + 1, endPre, in, i + 1, endIn);
break;
}
}
return root;
}
}
运行时间:185ms
占用内存:22612k
// 注意特殊输入测试:二叉树的根节点指针为null,输入的前序遍历序列和中序遍历序列不匹配

本文介绍了一种从给定的前序遍历和中序遍历结果重建二叉树的方法,并提供了一个Java实现示例。通过递归地确定根节点,并将中序序列分为左子树和右子树部分,最终重构完整的二叉树。
420

被折叠的 条评论
为什么被折叠?



