-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathkth-smallest-element-in-a-bst.py
More file actions
35 lines (32 loc) · 1.01 KB
/
kth-smallest-element-in-a-bst.py
File metadata and controls
35 lines (32 loc) · 1.01 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
class Solution:
def traverse_tree_rec(self, root):
result = []
if root.left is not None:
result += self.traverse_tree(root.left)
result.append(root)
if root.right is not None:
result += self.traverse_tree(root.right)
return result
def traverse_tree(self, root, k):
stack = [root]
node = None
count = 0
while len(stack):
if stack[-1].left is not None and \
stack[-1].left is not node and \
(node is None or node.right is not None):
stack.append(stack[-1].left)
else:
node = stack.pop()
count += 1
if count == k:
return node
if node.right is not None:
stack.append(node.right)
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
return self.traverse_tree(root, k).val