From the course: Data Structures in JavaScript: Trees and Graphs
Unlock this course with a free trial
Join today to access over 25,600 courses taught by industry experts.
Solution: Find the Kth smallest element in BST
From the course: Data Structures in JavaScript: Trees and Graphs
Solution: Find the Kth smallest element in BST
(upbeat music) - [Instructor] In this video, we will solve a classic BST problem, finding the kth smallest element. You are given a root of a valid BST and a number k. Your task is to return the kth smallest element in the tree. Let's start by recalling a key property of BSTs. If you do an in-order traversal, the left to the root to the right, the values will be sorted in that order. That's our key here. Let's look at example one. If we do an in-order traversal, we visit nodes in this order, one, two, three, and four. So if k is equal to one, the result is one, the smallest element. Let's look at example number two. In-order traversal gives us one, two, three, four, five, and six. So if k equals three, the result is three, the third smallest. Because of this, we'll perform an in-order traversal and count how many nodes we've seen. We start with a count initialized to zero. It tracks the number of nodes we've visited so far during our in-order traversal. We also would want to declare a…
Contents
-
-
-
-
-
(Locked)
Binary search tree concept5m 30s
-
(Locked)
Binary search tree implementation: insert3m 14s
-
Binary search tree implementation: search1m 24s
-
(Locked)
Binary search tree implementation: delete4m 9s
-
(Locked)
Solution: Validate a binary tree as BST7m 13s
-
(Locked)
Solution: Find the Kth smallest element in BST4m 18s
-
(Locked)
-
-
-
-