-
Notifications
You must be signed in to change notification settings - Fork 1
/
kth_greatest_node_bst.py
68 lines (50 loc) · 1.23 KB
/
kth_greatest_node_bst.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, Node):
if root == None:
root = Node
if root.val < Node.val:
if root.right is None:
root.right = Node
else:
insert(root.right, Node)
if root.val > Node.val:
if root.left is None:
root.left = Node
else:
insert(root.left, Node)
r = Node(3)
insert(r, Node(1))
insert(r, Node(4))
insert(r, Node(2))
# insert(r, Node(99))
# insert(r, Node(97))
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def kth_larger_node(root, k, count):
if root is None or count == k:
return
# count += 1
kth_larger_node(root.right, k, count)
count[0] += 1
if count[0] == k:
print(root.val)
kth_larger_node(root.left, k, count)
# kth_larger_node(r,6,[0])
# method 2
def kth_greatest_node(root, k):
arr = []
def inorder(root, arr):
if root:
inorder(root.left, arr)
arr.append(root.val)
inorder(root.right, arr)
inorder(r, arr)
print(arr[len(arr) - k])
kth_greatest_node(r, 2)