根据前序遍历序列和中序遍历序列重建二叉树

柔光的暖阳◎ 2022-07-16 03:40 282阅读 0赞

问题描述:

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

整体思路:

##前序遍历的第一个节点是根,在中序遍历中找到这个根所在的位置,那么中序遍历中根位置左边的便是整个树的左子树,根右边的是整个树的右子树,然后找到左子树的长度length,前序遍历中根节点之后的length个长度都是左子树的节点,然后对左子树找到根,再在其中序遍历中找到对应根的位置,依次递归即可(左子树构建完了就会依次构建右子树)。

#实现代码

  1. public class Main06{
  2. //定义树节点
  3. class TreeNode {
  4. int val;
  5. TreeNode left;
  6. TreeNode right;
  7. TreeNode(int x) {
  8. val = x; }
  9. }
  10. public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
  11. TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
  12. return root;
  13. }
  14. //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
  15. private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
  16. //如果起始下标大于结束下标,无效输入,终止程序
  17. if(startPre>endPre||startIn>endIn)
  18. return null;
  19. //前序遍历找到根节点
  20. TreeNode root=new TreeNode(pre[startPre]);
  21. for(int i=startIn;i<=endIn;i++)
  22. if(in[i]==pre[startPre]){
  23. //i-startIn是左子树节点的个数,前序遍历起始值加上这个就是终点值
  24. //i-1就是中序遍历左子树的终点,起始值是从0一直从0开始
  25. root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
  26. //前序右子树遍历的起始值:startPre+i-startIn+1 前序右子树遍历的终点值:endPre
  27. //中序遍历右子树的起始值:i+1,endIn
  28. root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
  29. }
  30. return root;
  31. }
  32. //中序遍历
  33. private List<Integer> listInorder=new ArrayList<Integer>() ;
  34. public void inOderPrint(TreeNode node){
  35. TreeNode temp=node;
  36. if(temp==null){
  37. throw new RuntimeException();
  38. }
  39. if(temp.left!=null){
  40. inOderPrint(temp.left);
  41. }
  42. listInorder.add(temp.val);
  43. if(temp.right!=null){
  44. inOderPrint(temp.right);
  45. }
  46. }
  47. private List<Integer> listPreorder=new ArrayList<Integer>() ;
  48. public void prePrint(TreeNode node){
  49. TreeNode temp=node;
  50. if(temp==null){
  51. throw new RuntimeException();
  52. }
  53. listPreorder.add(temp.val);
  54. if(temp.left!=null){
  55. prePrint(temp.left);
  56. }
  57. if(temp.right!=null){
  58. prePrint(temp.right);
  59. }
  60. }
  61. public static void main(String[] args) {
  62. Main06 m=new Main06();
  63. int[] preOrder={
  64. 1,2,4,7,3,5,6,8};
  65. int[] inOrder={
  66. 4,7,2,1,5,3,8,6};
  67. TreeNode node=m.reConstructBinaryTree(preOrder,inOrder);
  68. m.prePrint(node);
  69. m.inOderPrint(node);
  70. m.print(m.listPreorder);
  71. m.print(m.listInorder);
  72. }
  73. }

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读