Little Puzzlers–Is Tree a Binary Search Tree?

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

The Problem:

Given a standard definition of a binary tree node, i.e.:

1: public class Node

2: {

3: ​T Data { get; set; }

4: Node Left { get; set; }

5: Node Right { get; set; }

6: }

And a reference to the root of the tree:

1: Node root = ....;

Write a method that will determine if the tree has the ordered property.  A binary tree has the ordered property such that for any node x, the left sub-tree of x is < x and the right sub-tree of x is > x for all nodes. 

Examples:

That is, the following tree has the ordered property:

           5

        /    \        

      3        7      

    /   \     /       

   2     4   6     

But this tree does not:               

           5

        /    \        

      3        8      

    /   \     /       

   2     6   7     

Because even though 6 is on the right of 3 and is > 3, it is on the left sub-tree of 5 so it must be < 5.

Spoiler Alert

Fair Warning: discussion of the problem and potential solutions may be discussed in the comments below.

This article is part of the GWB Archives. Original Author: James Michael Hare

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.