I am stumped as to how to print the longest path from the root of a binary tree to a leaf, essentially traversing the height of the tree. I've got the following for finding the height of a binary tree:
if (root == null) {
return -1;
}
return 1 + (Math.max(heightOfTree(root.leftNode), heightOfTree(root.rightNode)));
This easily finds the height of the tree but doesn't lend itself to actually figuring out which nodes should be printed out. I could go about finding the nodes's value that is at the leaf, and then do a find for that particular node, but that seems inefficient.
A
B C
D E F G
H
For example, the height of this binary tree is 3, and I would ideally like to know the path to take, in this case it would be A, C, G, H. I know that I most likely need to keep an array for the path, but I just can't seem to find a solution that isn't terribly inefficient.