subject : Given a binary search tree , Please find the first one K Big / The first k Small nodes .
Binary search tree : The value of the root node is greater than that of any node in its left subtree , Less than the value of any node in its right node , This rule applies to every node in the binary lookup tree .
Pictured :
Ideas : Using the binary search tree feature , Stack .
Code :
# class root_tree:
# def f(self , root):
# self.root = root
# self.left = root.left
# self.right = root.right
class Solution:
def func_max(self , root , k):
stack = []
ans = root
while stack or root:
while root:
stack.append(root)
root = root.right
root = stack.pop()
k -= 1
ans = root
root = root.left
if k == 0:
return ans
def func_min(self , root , k):
stack = []
res = root
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
res = root
root = root.right
if k == 0:
return res