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

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

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
public class S2 {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode root=reConstruct(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    public TreeNode reConstruct(int []pre,int ps,int pe,int in[],int is,int ie){//保存子前序遍历序列和子中序遍历序列
        if(ps>pe||is>ie){
            return null;
        }
        TreeNode root=new TreeNode(pre[ps]); //每颗子树的根节点肯定是pre子数组的首元素,所以每次新建一个子树的根节点
        for(int i=is;i<=ie;i++){
            if(in[i]==pre[ps]){
                int num=i-is;//左子树的个数
                root.left=reConstruct(pre,ps+1,ps+num,in,is,i-1);//建立当前节点的左节点
                root.right=reConstruct(pre,ps+num+1,pe,in,i+1,ie);//建立当前节点的右节点
                break;
            }
        }
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/stubbornaccepted/article/details/79187336