Link: https://leetcode.com/problems/boundary-of-binary-tree/
Solution:
Topics: dfs
Intuition
This problem is a lot simpler than it appears. If you read carefully what constitutes a left and right boundary, you realize that its just a log(n) traversal down to the leftmost or rightmost node…storing every node on the way. The leaves can be obtained in the correct order (left first) with an o(n) depth first search.
There are a couple of edge cases. First, we want to make sure that we add the root at the end…this simplifies the logic. Second, we must ensure that we don’t add the leftmost and rightmost leaves twice (easy to miss since we would have already added these nodes in the left/right boundaries).
Implementation
Visual
Review 1
Just be mindful of the edge cases. Don’t add the root or leaf nodes in the left and right boundary traversal.