Approach
Depth-first search
For Boundary of Binary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 32 lines of Python from the credited upstream file 545.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def boundaryOfBinaryTree(self, root: TreeNode | None) -> list[int]:3 if not root:4 return []5 6 ans = [root.val]7 8 def dfs(root: TreeNode | None, lb: bool, rb: bool):9 """10 1. root.left is left boundary if root is left boundary.11 root.right if left boundary if root.left is None.12 2. Same applys for right boundary.13 3. If root is left boundary, add it before 2 children - preorder.14 If root is right boundary, add it after 2 children - postorder.15 4. A leaf that is neighter left/right boundary belongs to the bottom.16 """17 if not root:18 return19 if lb:20 ans.append(root.val)21 if not lb and not rb and not root.left and not root.right:22 ans.append(root.val)23 24 dfs(root.left, lb, rb and not root.right)25 dfs(root.right, lb and not root.left, rb)26 if rb:27 ans.append(root.val)28 29 dfs(root.left, True, False)30 dfs(root.right, False, True)31 return ans32