LeetCode: Kth Smallest Element in a BST Solution

Inorder traversal

Approach

Get the k-th element from result of inorder traversal

Implementation

1var kthSmallest = function (root, k) {
2 const traversed = []
3
4 const recursion = node => {
5 if (!node) return
6 recursion(node.left)
7 traversed.push(node.val)
8 recursion(node.right)
9 }
10
11 recursion(root)
12
13 return traversed[k - 1]
14}

References

Original problem

Similar problems

Binary Tree Inorder Traversal

Second Minimum Node In a Binary Tree

Comments

Loading comments...

Tags

leetcode

tree

binary tree

binary search tree

dfs

recursion

Next Post

LeetCode: Path Sum III

Sep 9, 2022

If timebox exceeded, read other solutions

Previous Post

LeetCode: Diameter of Binary Tree

Sep 5, 2022

Sum of max height of 2 subtrees

HoningJS

Search Posts