educative.io

IMHO some redundant variables and logic in Recursion solution

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

1 Like

Hello @Amit_Adiraju_Narasim,

Thank you for your feedback on the find_kth_max solution for BSTs. Your simplified approach indeed makes the code more understandable and likely faster by focusing directly on the tree’s properties without unnecessary variables like current_max.

We agree that leveraging the BST’s order with a simple counter to find the kth maximum value is more efficient and cleaner. Your input helps improve our solutions and encourages re-evaluation for better performance and simplicity.

Thanks for sharing your insights! Keep the great suggestions coming.