Kth Smallest Element in BST
230. Kth Smallest Element in a BST
Problem Description
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.
Intuition
Binary Tree
In BST, all nodes in the left subtree are smaller than the root. So if the left subtree has L nodes, the root is the (L+1)th smallest. We can use this to decide whether to go left, return current, or go right.
inorder
In BST, an inorder traversal visits nodes in sorted order, so the kth node visited is the kth smallest element.
Algorithm
1 | // BST |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 YouChen's Blog!