Find maximal uni-directional path length for a Binary Tree 1

Continuing from our last post for a Generic Binary Tree implementation, we’ve come up with a solution to quite an interesting problem.
We define a path in a binary tree to be a non-empty sequence of nodes that one can traverse by following the pointers in the nodes. A path only goes to the right if following this path we traverse only the right sub-tree pointers in nodes. Similarly it can be defined for a path going only to the left. We use the term unidirectional for such paths.

The problem here is to find the maximal length of any such unidirectional path that exists in a given tree. The output will be -1 if the tree is empty, and will be 0 if the tree has only the root node.
For the tree shown below:

Binary Tree: maximal unidirectional path to be found

Binary Tree: maximal unidirectional path to be found

there are multiple maximal unidirectional paths that exist in it. These are 5,3,4,6 (going left only starting from root), 5,10,11,13 (going right only) and 12,20,22,23 (again going right only but not beginning at the root). The output of code for finding the maximal unidirectional path length in each case would be 3 as three pointers/ links are to be traversed in each path.

This code is presented as part of the earlier GenericBinaryTree class’s code only. The earlier implementation can be found here.

Here goes the code for finding the same:

For using the above code a single statement is required after having created the tree itself:

Notice that the above code is also a modification to the previous code only which is also present in the previous post.

Rate this post

One comment on “Find maximal uni-directional path length for a Binary Tree

  1. Reply download web builder Feb 28,2018 8:19 pm

    Ԝay cool! Some very valid рoints! I appreciate you writing this post and also
    the rest of the site is alѕo reallү good.

Leave a Reply