Skip to content

Commit 0548d26

Browse files
committed
Adding Efficient Solution for Problem - 230 - Kth Smallest Element BST
1 parent ccfa4b7 commit 0548d26

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 230
6+
## Problem Name: Kth Smallest Element in a BST
7+
##===================================
8+
#
9+
#Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
10+
#
11+
#Note:
12+
#You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
13+
#
14+
#Example 1:
15+
#
16+
#Input: root = [3,1,4,null,2], k = 1
17+
# 3
18+
# / \
19+
# 1 4
20+
# \
21+
# 2
22+
#Output: 1
23+
#Example 2:
24+
#
25+
#Input: root = [5,3,6,2,4,null,null,1], k = 3
26+
# 5
27+
# / \
28+
# 3 6
29+
# / \
30+
# 2 4
31+
# /
32+
# 1
33+
#Output: 3
34+
class Solution:
35+
def kthSmallest(self, root, k):
36+
if root is None or k is None: #Condition-check: If root is null and k is null
37+
return None #We return None.
38+
tmp = [] #Initialize tmp empty list
39+
while True: #Loop while True
40+
while root: #Loop while root is not empty
41+
tmp.append(root) #Appned the root to tmp list
42+
root = root.left #Point reference to left sub-tree
43+
node = tmp.pop() #Initialize a node which will be last element of tmp list
44+
k = -1 #Update k by decreasing 1
45+
if not k: #Condition-check: If k's value is different
46+
return node.val #Return node's value
47+
root = root.right #Otherwise update root to root.right subtree for finding the smallest element

0 commit comments

Comments
 (0)