Kth Smallest Element in a BST

by atalaykutlay

Solution to "Kth Smallest Element in a BST" on Leetcode.

Kth Smallest Element in a BST
1# Definition for a binary tree node.
2# class TreeNode:
3#     def __init__(self, val=0, left=None, right=None):
4#         self.val = val
5#         self.left = left
6#         self.right = right
7class Solution:
8    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
9        
10        def tree_to_list(root) -> list:
11            if not root:
12                return []
13
14            return tree_to_list(root.right) + [root.val] + tree_to_list(root.left)
15        
16        tree_list = tree_to_list(root)
17        return tree_list[-k]

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python12 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python13 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python11 months ago