LeetCode #545 Medium

Boundary of Binary Tree

Boundary of Binary Tree is LeetCode 545 (Medium, premium). Given the root of a binary tree, return the values on its outline, going anticlockwise from the root:

  • the root;
  • the left boundary, top to bottom: start at root.left, and from each node go to its left child if it has one, otherwise to its right child;
  • every leaf, left to right;
  • the right boundary, bottom to top: the mirror of the left one, starting at root.right.

Neither boundary includes a leaf, a boundary is empty when the root has no child on that side, the root itself is never a leaf, and no node is listed twice. The tree can have 10⁴ nodes in a single chain, so deep recursion is a risk.

Constraints
  • The number of nodes in the tree is in the range [1, 10⁴].
  • -1000 <= Node.val <= 1000
treedfs
Open on LeetCode ↗
02

Intuition

The boundary is three simple walks plus the root. The only real difficulty is that the pieces touch: the bottom of the left boundary is a leaf, and so is the bottom of the right boundary. Give each node one owner:

  • Root: added first, on its own.
  • Boundary walks: add only nodes that are not leaves.
  • Leaf pass: adds every leaf, left to right.

With those rules each node lands in exactly one piece, so the pieces can simply be joined. The right boundary is collected top to bottom and reversed, because the anticlockwise outline climbs it from the bottom.

How to spot this pattern

Outline questions split the drawing of a tree into pieces with clear owners. Binary Tree Right Side View, the left view, Top View and Bottom View of a binary tree all ask which nodes sit on one edge of the drawing; boundary traversal joins several of those edges into one loop.

03

Approach

Try it first

Before reading on: in [1,2,3,4,5,6,null,null,null,7,8,9,10] node 4 is both the bottom of the left boundary and a leaf. Which of your passes should add it, and how does the other pass know to skip it?

1

Handle a lone root, then add the root

If the root has no children, return [root.val]. Otherwise start the answer with the root. The root is never treated as a leaf or as part of a boundary, so this is the only place it is added.

2

Walk the left boundary

Start at root.left. At each node, append its value unless it is a leaf, then move to its left child if it has one, otherwise to its right child. The walk ends at a leaf, which is left for the next pass.

3

Add every leaf, left to right

Start a stack with the root and pop until it is empty. A leaf is appended; any other node pushes its right child, then its left child, so the left side comes out first. An explicit stack keeps a 10⁴-deep chain from hitting the recursion limit.

4

Walk the right boundary and add it reversed

Start at root.right and mirror the left walk: keep non-leaf nodes, move right if possible, otherwise left. Collect them in a separate list and append it reversed, because the anticlockwise outline climbs the right side from the bottom.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
▶3 def is_leaf(node):
▶4 return not node.left and not node.right
▶5 
▶6 if is_leaf(root):
▶7 return [root.val]
▶8 result = [root.val]
▶9 
▶10 node = root.left
▶11 while node:
▶12 if not is_leaf(node):
▶13 result.append(node.val)
▶14 node = node.left if node.left else node.right
▶15 
▶16 stack = [root]
▶17 while stack:
▶18 node = stack.pop()
▶19 if is_leaf(node):
▶20 result.append(node.val)
▶21 else:
▶22 if node.right:
▶23 stack.append(node.right)
▶24 if node.left:
▶25 stack.append(node.left)
▶26 
▶27 right = []
▶28 node = root.right
▶29 while node:
▶30 if not is_leaf(node):
▶31 right.append(node.val)
▶32 node = node.right if node.right else node.left
▶33 result.extend(reversed(right))
▶34 return result
right listin answer12345678910answer1stackemptyrightemptyroot 1 goes first
result[1]
The root opens the boundary. It is added here and nowhere else: neither boundary walk starts at the root, and the leaf pass never sees it as a leaf because it has children.
right listin answer12345678910answer12stackemptyrightemptyleft boundary: add 2
node2not a leaf
next4left child
result[1, 2]
2 is on the left boundary and is not a leaf, so add it. Then move to its left child 4.
right listin answer12345678910answer12stackemptyrightempty4 is a leaf → leave it for the leaf pass
node4a leaf
result[1, 2]unchanged
4 ends the left boundary, but it is a leaf. The leaf pass owns every leaf, so skip it here; adding it now would list it twice. It has no children, so the walk stops.
right listin answer12345678910answer12stack32toprightemptypop 1: not a leaf → push 3, then 2
pop1has children
stack[3, 2]top on the right
Now collect the leaves, starting from a stack holding the root. Pop 1. It has children, so it is not a leaf; push the right child 3 first and the left child 2 on top, so the left side is searched first and the leaves come out left to right.
right listin answer12345678910answer12stack354toprightemptypop 2: not a leaf → push 5, then 4
pop2has children
stack[3, 5, 4]top on the right
Pop 2. It has children, so it is not a leaf; push the right child 5 first and the left child 4 on top.
right listin answer12345678910answer124stack35toprightemptypop 4: leaf → add
pop4a leaf
stack[3, 5]top on the right
result[1, 2, 4]
Pop 4. It is a leaf, so it joins the answer. The next pop is 5, the nearest subtree still waiting to its right.
right listin answer12345678910answer124stack387toprightemptypop 5: not a leaf → push 8, then 7
pop5has children
stack[3, 8, 7]top on the right
Pop 5. It has children, so it is not a leaf; push the right child 8 first and the left child 7 on top.
right listin answer12345678910answer1247stack38toprightemptypop 7: leaf → add
pop7a leaf
stack[3, 8]top on the right
result[1, 2, 4, 7]
Pop 7. It is a leaf, so it joins the answer. The next pop is 8, the nearest subtree still waiting to its right.
right listin answer12345678910answer12478stack3toprightemptypop 8: leaf → add
pop8a leaf
stack[3]top on the right
result[1, 2, 4, 7, 8]
Pop 8. It is a leaf, so it joins the answer. The next pop is 3, the nearest subtree still waiting to its right.
right listin answer12345678910answer12478stack6toprightemptypop 3: not a leaf → push 6
pop3has children
stack[6]top on the right
Pop 3. It has children, so it is not a leaf; push its only child 6.
right listin answer12345678910answer12478stack109toprightemptypop 6: not a leaf → push 10, then 9
pop6has children
stack[10, 9]top on the right
Pop 6. It has children, so it is not a leaf; push the right child 10 first and the left child 9 on top.
right listin answer12345678910answer124789stack10toprightemptypop 9: leaf → add
pop9a leaf
stack[10]top on the right
result[1, 2, 4, 7, 8, 9]
Pop 9. It is a leaf, so it joins the answer. The next pop is 10, the nearest subtree still waiting to its right.
right listin answer12345678910answer12478910stackemptyrightemptypop 10: leaf → add
pop10a leaf
stack[]top on the right
result[1, 2, 4, 7, 8, 9, 10]
Pop 10. It is a leaf, so it joins the answer. The stack is now empty, so every leaf is in, in left-to-right order.
right listin answer12345678910answer12478910stackemptyright3right boundary: keep 3 for later
node3not a leaf
next6no right child, so left
right[3]
3 is on the right boundary and is not a leaf. Put it in the separate right list, not the answer: this walk goes top to bottom, but the answer needs the right side bottom to top. Then move to its left child 6, because it has no right child.
right listin answer12345678910answer12478910stackemptyright36right boundary: keep 6 for later
node6not a leaf
next10right child
right[3, 6]
6 is on the right boundary and is not a leaf. Put it in the separate right list, not the answer: this walk goes top to bottom, but the answer needs the right side bottom to top. Then move to its right child 10.
right listin answer12345678910answer12478910stackemptyright3610 is a leaf → already added
node10a leaf
right[3, 6]unchanged
10 ends the right boundary, but it is a leaf, and the leaf pass already added it. Skip it; the walk stops here.
right listin answer12345678910answer1247891063stackemptyrightemptyadd right list reversed → 9 nodes
right[3, 6]top to bottom
result[1, 2, 4, 7, 8, 9, 10, 6, 3]root, left, leaves, right
Done. Append the right list in reverse, so the outline climbs the right side from the bottom back towards the root. Every node was added by exactly one piece, so the answer has no repeats.
05

Common pitfalls

Adding leaves during the boundary walks

✗ Wrong
while node:
    result.append(node.val)
    node = node.left if node.left else node.right
✓ Right
while node:
    if not is_leaf(node):
        result.append(node.val)
    node = node.left if node.left else node.right

Each walk ends at a leaf, and the leaf pass adds every leaf. Without the check, the bottom node of each boundary appears twice, for example 4 in [1,2,3,4].

Following only left children down the left boundary

✗ Wrong
node = node.left
✓ Right
node = node.left if node.left else node.right

The left boundary is the leftmost path, which goes through a right child when there is no left one. For [1,2,3,null,4,null,null,5,6] the boundary is [1, 2, 4, 5, 6, 3]; stopping at 2 loses 4.

Not returning early for a lone root

✗ Wrong
result = [root.val]
# then the walks and the leaf pass
✓ Right
if is_leaf(root):
    return [root.val]

A root with no children looks like a leaf to the leaf pass, which adds it again. The answer for [1] would be [1, 1] instead of [1].

06

Edge cases

Root without a left child

The left boundary is empty; the walk does not move into the right subtree. For [1,null,2,3,4] the answer is [1, 3, 4, 2].

07

Complexity

Time
O(n)
Space
O(h)
The leaf pass visits each node once and the two boundary walks follow one path each. Besides the answer, the stack and the right-boundary list hold O(h) nodes.
08

Boundary of Binary Tree FAQ

Is GFG Boundary Traversal of binary tree the same as LeetCode 545?

Yes. GeeksforGeeks asks for the same anticlockwise boundary traversal with the same rules: leaves are not part of either boundary, a missing side gives an empty boundary, and the right side is read bottom to top. LeetCode 545 is premium, so the GFG version is the free place to submit this code.

Is the left boundary the same as the left view?

No. The left view takes the first node on every level, which can come from the right subtree. The left boundary only follows the path from root.left downward and stops at a leaf. In [1,2,3,null,null,4] the left view is [1, 2, 4], but 2 is a leaf, so the left boundary is empty and 4 is added only as a leaf.