1008. Construct Binary Search Tree from Preorder Traversal Medium
1/**
2 * [1008] Construct Binary Search Tree from Preorder Traversal
3 *
4 * 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.
5 * It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
6 * 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.
7 * A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
8 *
9 * Example 1:
10 * <img alt="" src="https://assets.leetcode.com/uploads/2019/03/06/1266.png" style="height: 386px; width: 590px;" />
11 * Input: preorder = [8,5,1,7,10,12]
12 * Output: [8,5,10,1,7,null,12]
13 *
14 * Example 2:
15 *
16 * Input: preorder = [1,3]
17 * Output: [1,null,3]
18 *
19 *
20 * Constraints:
21 *
22 * 1 <= preorder.length <= 100
23 * 1 <= preorder[i] <= 1000
24 * All the values of preorder are unique.
25 *
26 */
27pub struct Solution {}
28use crate::util::tree::{TreeNode, to_tree};
29
30// problem: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
31// discuss: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34
35// Definition for a binary tree node.
36// #[derive(Debug, PartialEq, Eq)]
37// pub struct TreeNode {
38// pub val: i32,
39// pub left: Option<Rc<RefCell<TreeNode>>>,
40// pub right: Option<Rc<RefCell<TreeNode>>>,
41// }
42//
43// impl TreeNode {
44// #[inline]
45// pub fn new(val: i32) -> Self {
46// TreeNode {
47// val,
48// left: None,
49// right: None
50// }
51// }
52// }
53use std::rc::Rc;
54use std::cell::RefCell;
55impl Solution {
56 pub fn bst_from_preorder(preorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
57 Some(Rc::new(RefCell::new(TreeNode::new(0))))
58 }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_1008() {
69 }
70}
71
Back
© 2025 bowen.ge All Rights Reserved.