【LeetCode】105. 从前序与中序遍历序列构造二叉树 106. 从中序与后序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树

这道题也是经典的数据结构题了,有时候面试题也会遇到,已知前序与中序的遍历序列,由前序遍历我们可以知道第一个元素就是根节点,而中序遍历的特点就是根节点的左边全部为左子树,右边全部为右子树,再依次遍历前序序列,分割中序序列,不断结合这两个序列,就可以写代码了。详细说明都在代码中。因为前序是根左右,中序是左根右。

算法代码

class Solution {
    private int preindex;  //成员变量 是遍历前序数组的索引 弄成成员变量比较好
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inleft,int inright){

        if(inleft>inright) return null;  //说明当前节点无左右子节点了
        TreeNode root = new TreeNode(preorder[preindex]);
        int index = find(inorder,preorder[preindex]); //找在中序数组中的索引,用来分组
        preindex++; 
        root.left = buildTreeChild(preorder,inorder,inleft,index-1); //先递归并返回当前节点的左子节点
        root.right = buildTreeChild(preorder,inorder,index+1,inright); //后递归并返回当前节点的右子节点
        return root;  //最后返回当前节点

    }

    public static int find(int[] inorder,int key){ //用来找每个根节点在后序数组中的下标,并返回下标
        int i = 0;
        while(inorder[i]!=key){
            i++;
        }
        return i;
    }
}

106. 从中序与后序遍历序列构造二叉树

此题与上个题几乎一模一样,区别在于,是已知中序和后序,而后序的特点是最后一个元素,为根节点,故要对后序序列进行从后往前遍历。并且递归返回左右子树的顺序也要发生改变。剩下的就和前一个代码一样了。因为中序是左根右,后序是左右根。

算法代码

class Solution {

    private int postindex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postindex = postorder.length-1;  //指向序列最后一个元素,倒序遍历
        return buildTreeChild(postorder,inorder,0,postorder.length-1);

    }

     private TreeNode buildTreeChild(int[] postorder,int[] inorder ,int inleft,int inright){
        if(inleft>inright) return null;
        TreeNode root = new TreeNode(postorder[postindex]);
        int index = find(inorder,postorder[postindex]);
        postindex--;
        root.right = buildTreeChild(postorder,inorder,index+1,inright); //这里有区别
        root.left = buildTreeChild(postorder,inorder,inleft,index-1); //有区别
        return root;

    }
    private static int find(int[] inorder,int key){
        int i = 0;
        while(inorder[i] != key){
            i++;
        }
        return i;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_73381672/article/details/132095169