剑指offer之面试题6:重建二叉树

来源:互联网 发布:深圳网络运营策划公司 编辑:程序博客网 时间:2024/06/06 02:59

题目描述

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

思路:二叉树前(先)序遍历:根,左,右;中序遍历:左,根,右;(注:先,中指的是根)。根据前序遍历序列可以得到此二叉树的根为1。再根据中序遍历序列,可知在1左边的为根的左子树中序遍历序列{4,7,2},右边的为根的右子树中序遍历序列{5,3,8,6}。知道左右子树的个数,再回到前序遍历可以得到根节点后面3个连续数字是左子树的前序遍历序列{2,4,7},剩下的是右子树的前序遍历序列{3,5,6,8}。既然得到了左右子树的前序和中序遍历序列,可以用递归来实现。

这里写图片描述

贴出实现的代码,在牛客OJ提交成功:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {        if(pre==null||in==null||pre.length<=0||pre.length!=in.length)            return null;        return ConstructCore(pre, 0, pre.length-1, in, 0, in.length-1);    }    public static TreeNode ConstructCore(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn){        //初始化根节点        int rootValue=pre[startPre];        TreeNode root = new TreeNode(rootValue);        root.val=rootValue;        root.left=root.right=null;        if(startPre==endPre){            if(startIn==endIn&&pre[startPre]==in[startPre]){                return root;            }            /*else{                System.out.println("Invalid input");            }*/        }        //在中序遍历中找根节点        int rootInorder=startIn;        while(rootInorder<=endIn&&in[rootInorder]!=rootValue){            rootInorder++;        }        if(rootInorder==endIn&&in[rootInorder]!=rootValue){            System.out.println("Invalid input");        }        int leftLength=rootInorder-startIn;        int leftPreEnd=startPre+leftLength;        if(leftLength>0){            root.left=ConstructCore(pre, startPre+1, leftPreEnd, in, startIn, rootInorder-1);        }        if(leftLength<endPre-startPre){            root.right=ConstructCore(pre, leftPreEnd+1, endPre, in, rootInorder+1, endIn);        }        return root;    }    public static void main(String[] args){        int[] pre={1,2,4,7,3,5,6,8};        int[] in={4,7,2,1,5,3,6,8};        System.out.println(reConstructBinaryTree(pre,in).toString());    }}
0 0
原创粉丝点击