Leetcode #545: Boundary of Binary Tree
In this guide, we solve Leetcode #545 Boundary of Binary Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary. The left boundary is the set of nodes defined by the following: The root node's left child is in the left boundary.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: root = [1,null,2,3,4]
Output: [1,3,4,2]
Explanation:
- The left boundary is empty because the root does not have a left child.
- The right boundary follows the path starting from the root's right child 2 -> 4.
4 is a leaf, so the right boundary is [2].
- The leaves from left to right are [3,4].
Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2].
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
def dfs(nums: List[int], root: Optional[TreeNode], i: int):
if root is None:
return
if i == 0:
if root.left != root.right:
nums.append(root.val)
if root.left:
dfs(nums, root.left, i)
else:
dfs(nums, root.right, i)
elif i == 1:
if root.left == root.right:
nums.append(root.val)
else:
dfs(nums, root.left, i)
dfs(nums, root.right, i)
else:
if root.left != root.right:
nums.append(root.val)
if root.right:
dfs(nums, root.right, i)
else:
dfs(nums, root.left, i)
ans = [root.val]
if root.left == root.right:
return ans
left, leaves, right = [], [], []
dfs(left, root.left, 0)
dfs(leaves, root, 1)
dfs(right, root.right, 2)
ans += left + leaves + right[::-1]
return ans
Complexity
The time complexity is and the space complexity is , where is the number of nodes in the binary tree. The space complexity is , where is the number of nodes in the binary tree.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.