由前序和中序序列构造二叉树

在这里插入图片描述
思路:
在前序序列中找根结点,利用根结点将中序序列分成两部分(分别是左、右子树)。然后找到左子树的根结点和右子树的根结点,然后再将中序序列已经分好的两部分进行分割,一直递归下去,直到没有子树存在。

class Solution {
    
    

    HashMap<Integer,Integer> map=new HashMap<>();
    int[] po;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
    
    
        if(preorder==null||preorder.length==0)
            return null;
        po=preorder;
        for(int i=0;i<inorder.length;i++) 
            map.put(inorder[i],i);
        return build(0,0,inorder.length-1);
    }

	//三个参数为:根结点在前序序列中的下标,左边界,右边界
    public TreeNode build(int rootIndex,int startIndex,int endIndex){
    
    
    	//递归停止条件:不存在子树
        if(startIndex>endIndex)
            return null;
        //根结点
        int rootVal=po[rootIndex];
        TreeNode root=new TreeNode(rootVal);
        //根结点在中序序列中的位置
        int i=map.get(rootVal);
        //左子树的根结点为当前根结点的下一个
        root.left=build(rootIndex+1,startIndex,i-1);
        //右子树的根结点为:根结点位置+左子树长度+1
        root.right=build(rootIndex+i-startIndex+1,i+1,endIndex);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42451178/article/details/107292318