Reflection — Longest Path Of A Node

Raymond Lo

Raymond Lo October 14, 2022

2 min read

This is more of a personal journal post for me to answer my own questions and clear any misconceptions I have, so I can get a better understanding about the problem and topic. I'm hopeful that this will also help people that are relatively new to the concepts.

I was given a real-life application question involving a tree data structure. After going over the question and thinking about it, I realized it was asking me to find the longest path of a given node in a tree. Honestly, it was quite wordy and I could've saved a lot of time if I started with drawing out the problem.

After determining the type of question, I should begin considering possible tools I can use to solve the question. In our case, tree traversal algorithms like breadth-first search (BFS) and depth-first search (DFS) come to mind as you're typically searching for a solution node in the tree. The solution node would be the node furthest from our given node because we're trying the find the longest path.

I also didn't realize this until now, but the longest path of a node is the same as the height of the node. I came across this amazing answer on StackOverflow that helped me understand the height and depth properties of nodes and trees better.

There are more tree traversal algorithms than the two mentioned, however BFS and DFS are the most common. Both can be used here to solve our problem, but is one better than the other? There are various practical factors that can help you decide, but in general it depends on the structure of the tree. BFS also typically uses a queue data structure, which would require more space than the recursion DFS approach which only uses the call stack.