Get a free weekly practice problem!

Keep that axe sharp.

× No thanks

You only have free questions left (including this one).

But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.

Write a function to find the 2nd largest element in a binary search tree.

Here's a sample binary tree node class:

class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right

Our first thought might be to do an in-order traversal of the BST and return the second-to-last item. This means looking at every node in the BST. That would take time and space, where h is the max height of the tree (which is lg(n) if the tree is balanced, but could be as much as n if not).

We can do better than time and space.

We can do this in one walk from top to bottom of our BST. This means time (again, that's if the tree is balanced, otherwise).

A clean recursive implementation will take space in the call stack, but we can bring our algorithm down to space overall.

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

We're doing one walk down our BST, which means time, where h is the height of the tree (again, that's if the tree is balanced, otherwise). space.

Start your free trial!

Log in or sign up with one click to get immediate access to free mock interview questions

Reset editor

Powered by qualified.io

. . .