-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathKthNodeInBST.py
51 lines (51 loc) · 1.3 KB
/
KthNodeInBST.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
41
42
43
44
45
46
47
48
49
50
51
### Solution 1:
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
res = 0
if root is None or k < 1:
return res
out = []
self.helper(root, out)
res = out[-k]
return res
def helper(self, root, out):
if root is None:
return
self.helper(root.left, out)
out.append(root.val)
self.helper(root.right, out)
### Solution 2:
class Solution:
def __init__(self):
self.res = 0
self.count = 0
def kthLargest(self, root: TreeNode, k: int) -> int:
if root is None or k < 1:
return self.res
self.helper(root, k)
return self.res
def helper(self, root, k):
if (root==None):
return
self.helper(root.right, k)
self.count = self.count + 1
if self.count == k:
self.res = root.val
return
self.helper(root.left, k)
### Solution 3:
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
n = 0
s = []
p = root
while s or p:
while p:
s.append(p)
p = p.right
p = s.pop()
n+=1
if n == k:
return p.val
p = p.left
return 0