In my humble opinion, solution with recursive approach has some redundant logic and variables.
The below recursion logic passes all test cases and simplifies approach for better understanding, even runs faster in my opinion.
def rec_kth_max(root, k):
global counter
if root == None: return None
child_node = rec_kth_max(root.rightChild, k)
if counter != k:
counter +=1
if counter == k:
# If child node is not None, some node
# below right child contains kth max node
if child_node != None: return child_node
# current node is kth max
else: return root
else:
# If came here, root is not kth max,
# so it should be to left of root
return rec_kth_max(root.leftChild, k)
I was finding it hard to reason why we need “current_max” and additional elif statements in the original solution, Could anybody throw some light on this please.
Course: https://www.educative.io/collection/5642554087309312/5634727314718720
Lesson: https://www.educative.io/collection/page/5642554087309312/5634727314718720/5722608653828096