Construct Binary Search Tree from Preorder Traversal 之 二叉树递归

本题目过于经典,所以在这里好好记录一下。

总共有三种解法

1.因为二叉搜索树的特性,将preorder数组排序,得到inorder。再将inorder的元素和下标用map存储起来,再对其进行递归。

2.利用二叉树的特性,初始化最小值,最大值,进行递归

3.用栈结构进行迭代。

 

class Solution {
    int[] preorder;
    int idx = 0;
    Map<Integer, Integer> map_inorder = new HashMap<>();
    public TreeNode bstFromPreorder(int[] preorder) {
        this.preorder = preorder;
        int[] inorder = Arrays.copyOf(preorder, preorder.length);
        Arrays.sort(inorder);
        int n = inorder.length;
        for(int i = 0; i < n; i++){
            map_inorder.put(inorder[i], i);
        }
        return helper(0, n);
    }
    public TreeNode helper(int left, int right){
        if(left == right) return null;
        int val = preorder[idx];
        TreeNode root = new TreeNode(val);
        int index = map_inorder.get(val);
        idx++;
        root.left = helper(left, index);
        root.right = helper(index+1, right);
        return root;
    }
}

 

class Solution {
    int[] preorder;
    int idx = 0;
    int n;
    public TreeNode bstFromPreorder(int[] preorder) {
        this.preorder = preorder;
        n = preorder.length; 
        return helper(Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    public TreeNode helper(int lower, int upper){
        if(idx == n) return null;
        int val = preorder[idx];
        if(val < lower || val > upper) return null;//
        idx++;
        TreeNode root = new TreeNode(val);
        root.left = helper(lower, val);
        root.right = helper(val, upper);
        return root;
    }
}

 

class Solution {
    public TreeNode bstFromPreorder(int[] preorder) {
        int n = preorder.length;
        if(n == 0) return null;
        TreeNode root = new TreeNode(preorder[0]);
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.addLast(root);
        for(int i = 1; i < n; i++){
            TreeNode node = stack.getLast();
            TreeNode child = new TreeNode(preorder[i]);
            while(!stack.isEmpty() && stack.getLast().val < child.val){
                node = stack.removeLast();
            }
            if(node.val < child.val) node.right = child;
            else node.left = child;
            stack.addLast(child);
        }
        return root;
    }
}

 

posted @ 2020-06-01 17:59  yawenw  阅读(205)  评论(0编辑  收藏  举报