Skip to main content

Kth Smallest Element in a BST

Question

Given a binary search tree, find the kth smallest element in the tree.

Example 1
None

Solution

all//Kth Smallest Element in a BST.py


# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def kthSmallest(self, root, k):
#inorder traversal
def inorder(node):
if node == None:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
arr = inorder(root)
return arr[k-1]