1008. 前序遍历构造二叉搜索树

130 阅读1分钟

给定一个整数数组,它表示BST(即 二叉搜索树 )的  序遍历 ,构造树并返回其根。

保证 对于给定的测试用例,总是有可能找到具有给定需求的二叉搜索树。

二叉搜索树 是一棵二叉树,其中每个节点, Node.left 的任何后代的值严格小于 Node.val , Node.right 的任何后代的值 严格大于 Node.val

二叉树的 前序遍历 首先显示节点的值,然后遍历Node.left,最后遍历Node.right

示例 1:

image.png

输入: preorder = [8,5,1,7,10,12]
输出: [8,5,10,1,7,null,12]

示例 2:

输入: preorder = [1,3]
输出: [1,null,3]

题解 :


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @return {TreeNode}
 */
var bstFromPreorder = function (preorder) {
    const func = (preorder, start, end) => {
        if (start > end) return null;
        // 根据前序遍历的特点,根节点在第一位,后面接着左子树和右子树
        let rootVal = preorder[start];
        // 创建节点
        let root = new TreeNode(rootVal);
        // rootIndex 就是左右子树的分界点
        let rootIndex = start;
        while (rootIndex <= end) { // 边界判断
            // 根据 BST 的特点,左子树都比根节点的值小,右子树都比根节点的值大
            if (preorder[rootIndex] > preorder[start]) break
            rootIndex++
        }
        root.left = func(preorder, start + 1, rootIndex - 1) // 左子树元素
        root.right = func(preorder, rootIndex, end) // 右子树元素
        return root

    }
    return func(preorder, 0, preorder.length - 1)

};

来源:力扣(LeetCode)

链接:leetcode.cn/problems/co…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。