Navigator_Z头像
LeetCode //C - 1008. Construct Binary Search Tree from Preorder Traversal封面图

LeetCode //C - 1008. Construct Binary Search Tree from Preorder Traversal

1008. Construct Binary Search Tree from Preorder Traversal

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
 

Example 1:

在这里插入图片描述

Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Example 2:

Input: preorder = [1,3]
Output: [1,null,3]

Constraints:
  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 1000
  • All the values of preorder are unique.

From: LeetCode
Link: 1008. Construct Binary Search Tree from Preorder Traversal


Solution:

Ideas:
  • Preorder property: The first value in preorder is always the root of the tree/subtree.

  • BST rule:

    • Left subtree values < root
    • Right subtree values > root
  • Use a global index (idx) to read elements from the preorder array sequentially.

  • Use value bounds (low, high) to ensure each node follows BST rules.

  • If the current value is outside the allowed range, return NULL.

  • Otherwise:

    • Create a node with the current value.
    • Recursively build the left subtree with range (low, root->val).
    • Recursively build the right subtree with range (root->val, high).
  • Continue until all preorder elements are used.

Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

static struct TreeNode* newNode(int v) {
    struct TreeNode* n = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    n->val = v;
    n->left = NULL;
    n->right = NULL;
    return n;
}

/* Build BST from preorder using value bounds: (low, high) exclusive */
static struct TreeNode* build(int* preorder, int n, int* idx, long low, long high) {
    if (*idx >= n) return NULL;

    int v = preorder[*idx];
    if ((long)v <= low || (long)v >= high) return NULL;

    struct TreeNode* root = newNode(v);
    (*idx)++;

    root->left  = build(preorder, n, idx, low, (long)v);
    root->right = build(preorder, n, idx, (long)v, high);

    return root;
}

struct TreeNode* bstFromPreorder(int* preorder, int preorderSize) {
    int idx = 0;
    return build(preorder, preorderSize, &idx, LONG_MIN, LONG_MAX);
}

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/navicheung/article/details/158661398

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--