【剑指Offer】04、重建二叉树

题目描述

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

题解:递归
 1 public static TreeNode reConstructBinaryTree(int[] pre,int[] in) {
 2         if(pre.length==0||in.length==0){
 3             return null;
 4         }
 5         TreeNode treeNode = new TreeNode(pre[0]);
 6         for(int i=0;i<in.length;i++){
 7             if(in[i]==pre[0]){
 8                 //中序遍历中根节点的位置
 9                 int index=i;
10                 treeNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,index+1), Arrays.copyOfRange(in,0,index));
11                 treeNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,index+1,pre.length), Arrays.copyOfRange(in,index+1,in.length));
12             }
13         }
14         return treeNode;
15     }

结构定义:

1 public static class TreeNode {
2       int val;
3       TreeNode left;
4       TreeNode right;
5       TreeNode(int x) { val = x; }
6   }

后序打印:

1 //后序遍历打印输出
2     public static void print(TreeNode root){
3         if(root==null){
4             return;
5         }
6         print(root.left);
7         print(root.right);
8         list.add(root);
9     }

测试:

 1 static ArrayList<TreeNode> list=new ArrayList<TreeNode>();
 2     public static void main(String[] args) {
 3         int[] pre={1,2,4,7,3,5,6,8};
 4         int[] in={4,7,2,1,5,3,8,6};
 5         TreeNode treeNode = reConstructBinaryTree(pre, in);
 6         print(treeNode);
 7         for (TreeNode node : list) {
 8            System.out.print(node.val+" ");
 9         }
10     }
11 //输出:
12 //7 4 2 5 8 6 3 1

猜你喜欢

转载自www.cnblogs.com/Blog-cpc/p/12339658.html