Solving Kth Smallest Element in a BST: Navigating Tree Order
The "Kth Smallest Element in a BST" problem requires finding the kth smallest element in a Binary Search Tree (BST). This problem can be effectively tackled by understanding and utilizing the properties of BSTs, particularly inorder traversal.
Problem Statement
Given the root of a binary search tree and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example
Consider a binary search tree:
Example 1:

Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Solution Approach - Inorder Traversal
Breaking Down the Solution
- Map for Inorder Indices: Create a map to quickly find the index of each value in the inorder sequence.
- Recursive Construction: Recursively build the left and right subtrees using the indices in the map to find the dividing point.
- Preorder Traversal: The preorder array guides the creation of each node, starting from the root.
Conclusion
Constructing a binary tree from preorder and inorder traversals is an intriguing challenge that tests understanding of tree properties and traversal techniques.
Rust Solution
Rust's stack is a Vec<&TreeNode> of shared borrows rather than owned nodes, so as_deref() is what peels each Option<Box<TreeNode>> down to an Option<&TreeNode> — you walk the tree without ever moving a boxed node out of it. The while let Some(node) = current and if let Some(node) = stack.pop() forms fold the null check and the binding into one step; because pop() already yields an Option, there is no separate undefined-handling branch like the TS version needs. The bare -1 on the last line is the function's return value, no return keyword required.
Go Solution
Go leans on a plain []*TreeNode slice as the stack: append(stack, current) pushes, and popping is a manual peek-then-reslice — stack[len(stack)-1] reads the top and stack = stack[:len(stack)-1] drops it. The *TreeNode pointer's zero value is nil, so current != nil and len(stack) > 0 serve as the loop guards, with no Option wrapper to unwrap as in Rust. A bare -1 is returned as the not-found sentinel.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.