The Kth smallest in Binary Search Tree
Medium; BST
Last updated
Medium; BST
Last updated
1. Link
2. 题目
230. Kth Smallest Element in a BST
Given the root
of a binary search tree, and an integer k
, return the kth
(1-indexed) smallest element in the tree.
3. 思路
Idea: Recursion of the Binary search tree
Input of recursion: parent node, k, the number of node smaller than parent
Output of recursion : either the found kth smallest node and it ranking k, or the maximum node value and the corresponding ranking (ascending ranking)
Idea
Iterate every node
first go to its left child to find the smallest node and its ranking
then find how many node is smaller than current node/left child and check if the returned result from left node or current node is the K^th smallest. If so, return result.
Then go to right child of current node with updated amount of node smaller than the right node.
Note that the main idea of this method is to label every node with its ranking based on BST property.
Time: O(n) to iterate every tree node. Space: O(logn) to store the depth of tree
4. Coding
Example 1:
Example 2: