1008. Construct Binary Search Tree from Preorder Traversal(根据先序遍历构建BST)

题目描述

Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

在这里插入图片描述

方法思路

class Solution {
    //Runtime: 1 ms, faster than 81.14%
    //Memory Usage: 36.9 MB, less than 100.00%
    public TreeNode bstFromPreorder(int[] preorder) {
        if(preorder.length == 0)
            return null;
        return help_bstFP(preorder, 0, preorder.length - 1);
    }
    public TreeNode help_bstFP(int[] preorder, int start, int end){
        if(start > end) 
            return null;
        if(start == end) 
            return new TreeNode(preorder[start]);
        TreeNode root = new TreeNode(preorder[start]);
        int index = 0;
        for(int i = start; i <= end; i++){
            if(preorder[i] > root.val){
                index = i;
                break;
            }
        }
        //需要考虑到只有左子树的情况如[4,2]
        if(index == 0){
            root.left = help_bstFP(preorder, start + 1, end);
        }else{
            root.left = help_bstFP(preorder, start + 1, index - 1);
            root.right = help_bstFP(preorder, index, end);
        }
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/IPOC_BUPT/article/details/88568165
今日推荐