The Kth smallest in Binary Search Tree

Medium; BST

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.

Example 1:

Example 2:

3. 思路

  1. Idea: Recursion of the Binary search tree

  2. Input of recursion: parent node, k, the number of node smaller than parent

  3. Output of recursion : either the found kth smallest node and it ranking k, or the maximum node value and the corresponding ranking (ascending ranking)

  4. Idea

    1. Iterate every node

    2. first go to its left child to find the smallest node and its ranking

    3. 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.

    4. Then go to right child of current node with updated amount of node smaller than the right node.

    5. Note that the main idea of this method is to label every node with its ranking based on BST property.

  5. Time: O(n) to iterate every tree node. Space: O(logn) to store the depth of tree

4. Coding

Last updated

Was this helpful?