LeetCode: Kth Smallest Element in a BST Solution
Inorder traversalApproach
Get the k-th element from result of inorder traversal
Implementation
1var kthSmallest = function (root, k) {2 const traversed = []34 const recursion = node => {5 if (!node) return6 recursion(node.left)7 traversed.push(node.val)8 recursion(node.right)9 }1011 recursion(root)1213 return traversed[k - 1]14}
References
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
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.