-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path230KthSmallestElementinaBST.py
40 lines (37 loc) · 1.04 KB
/
230KthSmallestElementinaBST.py
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
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
count = [0]
kmallest = [0]
def traverse(root):
if root.left:
traverse(root.left)
count[0] += 1
if count[0] == k:
kmallest[0] = root.val
return root.val
if root.right:
traverse(root.right)
traverse(root)
return kmallest[0]
def kthSmallest2(self, root, k):
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right