Quantcast
Channel: Geekswithblogs.net
Viewing all articles
Browse latest Browse all 3624

Little Puzzlers–Is Tree a Binary Search Tree?

$
0
0

Originally posted on: http://geekswithblogs.net/BlackRabbitCoder/archive/2015/03/23/little-puzzlersndashis-tree-a-binary-search-tree.aspx

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

   1:publicclass Node<T>
   2: {
   3:     ?T Data { get; set; }
   4:     Node<T> Left { get; set; }
   5:     Node<T> Right { get; set; }
   6: }

And a reference to the root of the tree:

   1: Node<T> 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. 

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.


Viewing all articles
Browse latest Browse all 3624