-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_Kth_element.py
More file actions
47 lines (35 loc) · 1.23 KB
/
Find_Kth_element.py
File metadata and controls
47 lines (35 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
current = root
while True:
# Go to the leftmost node
while current:
stack.append(current)
current = current.left
# Pop the node from the stack
current = stack.pop()
k -= 1
# If k is 0, we've found the k-th smallest element
if k == 0:
return current.val
# Move to the right node
current = current.right
Method 2:
# 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: Optional[TreeNode], k: int) -> int:
def inOrderTraversal(node, array):
if not node:
return None
inOrderTraversal(node.left, array)
array.append(node.val)
inOrderTraversal(node.right, array)
array = []
inOrderTraversal(root, array)
return array[k-1]