MEDIUM

DATA STRUCTURES AND ALGORITHMS

BINARY TREESDEPTH FIRST SEARCH (DFS)TREES

Written By

Tom Wagner

Kenny Polyak

The Boundary of Binary Tree coding problem involves traversing a given binary tree and identifying all nodes that are located on the boundary of the tree. The challenge is in traversing the tree such that the boundary nodes can be identified. This problem can be solved using depth-first search, breadth-first search, and iterative in-order traversal.

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. If the root does not have a left child, then the left boundary is empty. If a node is in the left boundary and has a left child, then the left child is in the left boundary. If a node is in the left boundary, has no left child, but has a right child, then the right child is in the left boundary. The leftmost leaf is not in the left boundary.

The right boundary is similar to the left boundary, except it is the right side of the root's right subtree. Again, the leaf is not part of the right boundary, and the right boundary is empty if the root does not have a right child.

The leaves are nodes that do not have any children. For this problem, the root is not a leaf.

Given the root of a binary tree, return the values of its boundary.

**Input:** root = [1,2,3,4,null,5,null]
**Output:** [1,2,4,5,3]

Explanation:

- The left boundary consists of just
`2`

(because`4`

is a leaf). - The right boundary consists of just
`3`

(because`5`

is a leaf). - The leaves consist of two nodes,
`4`

and`5`

.

**Input:** root = [1,2,3,4,null,6,7,null,5,null,null,null,8]
**Output:** [1,2,4,5,6,8,7,3]

The left boundary consists of `2`

and `4`

.
The leaves consist of `5`

, `6`

and `8`

.
The right boundary consists of `3`

and `7`

.

**Constraints**

- The number of nodes in the tree is in the range [1, 104].
- -1000 <= Node.val <= 1000

Start AI Interview

As with many other coding interview questions, this particular problem can be broken down into subproblems. And in this instance the problem itself provides a good guide; to find the boundary we need to find the left boundary, the leaves and the *reverse-order* of the right boundary.

Whenever we are tasked with traversing a binary tree, our first thought should be in regards to the traversal methods we have available, depth-first or breadth-first, and whether we should implement the algorithm iteratively or recursively. If we are focused on the leaves with a possibility of exiting early perhaps depth-first traversal would make sense. Conversely, if we need to split the tree into levels or focus on the top of the tree, then breadth-first might make more sense. To solve this problem though, we simply need to visit each node in the tree to determine if it is part of the boundary, so breadth-first or depth-first will both work.

We need to first find the values of the left edge of the tree. This can be done by traversing the left side of the tree and adding the values of the nodes to a list.

Next, we need to find the values of the leaves in the tree, which can be done by traversing the tree in-order and adding the values of the leaf nodes to a list. In-order traversal works well here (vs pre-order or post-order) given the requirement to keep the leaves in order from left to right.

Finally, we need to find the values of the right boundary of the tree, which can be done by traversing the right side of the tree and adding the values of the nodes to a list. Once we have these three lists, we can concatenate them to get the boundary of the binary tree.

```
class Solution:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
return (
[root.val] +
self.getLeftEdge(root.left, []) +
self.getLeaves(root, []) +
self.getRightEdge(root.right, [])
)
def getLeftEdge(self, node: Optional[TreeNode], left_boundary: List[int]) -> List[int]:
if not node or not node.left and not node.right:
return left_boundary
left_boundary.append(node.val)
if node.left:
return self.getLeftEdge(node.left, left_boundary)
else:
return self.getLeftEdge(node.right, left_boundary)
def getLeaves(self, root: Optional[TreeNode], leaves: List[int]) -> List[int]:
boundary = []
def recursively_get_leaves(node):
if not node:
return
recursively_get_leaves(node.left)
# if the node has no children it is a leaf node
if node != root and not node.left and not node.right:
boundary.append(node.val)
recursively_get_leaves(node.right)
recursively_get_leaves(root)
return boundary
def getRightEdge(self, node: Optional[TreeNode], right_boundary: List[int]) -> List[int]:
if not node or (not node.right and not node.left):
return right_boundary
if node.right:
right_boundary = self.getRightEdge(node.right, right_boundary)
else:
right_boundary = self.getRightEdge(node.left, right_boundary)
right_boundary.append(node.val)
return right_boundary
```

```
1class Solution:
2 def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
3 return (
4 [root.val] +
5 self.getLeftEdge(root.left, []) +
6 self.getLeaves(root, []) +
7 self.getRightEdge(root.right, [])
8 )
9
10 def getLeftEdge(self, node: Optional[TreeNode], left_boundary: List[int]) -> List[int]:
11 if not node or not node.left and not node.right:
12 return left_boundary
13
14 left_boundary.append(node.val)
15
16 if node.left:
17 return self.getLeftEdge(node.left, left_boundary)
18 else:
19 return self.getLeftEdge(node.right, left_boundary)
20
21 def getLeaves(self, root: Optional[TreeNode], leaves: List[int]) -> List[int]:
22 boundary = []
23
24 def recursively_get_leaves(node):
25 if not node:
26 return
27
28 recursively_get_leaves(node.left)
29
30 # if the node has no children it is a leaf node
31 if node != root and not node.left and not node.right:
32 boundary.append(node.val)
33
34 recursively_get_leaves(node.right)
35
36 recursively_get_leaves(root)
37 return boundary
38
39 def getRightEdge(self, node: Optional[TreeNode], right_boundary: List[int]) -> List[int]:
40 if not node or (not node.right and not node.left):
41 return right_boundary
42
43 if node.right:
44 right_boundary = self.getRightEdge(node.right, right_boundary)
45 else:
46 right_boundary = self.getRightEdge(node.left, right_boundary)
47
48 right_boundary.append(node.val)
49 return right_boundary
50
```

- Time complexity:
`O(n)`

, as each node in the binary tree is visited at most three times: once in`getLeftEdge`

, once in`getRightEdge`

, and once in`getLeaves`

.`O(3n)`

is the same from a Big-O notation perspective as`O(n)`

, so we drop the constant and simply go with`O(n)`

. - Space complexity:
`O(n)`

. The algorithm stores the values of the left edge, the leaves, and the right edge in three separate lists. The space complexity is linear because the size of the lists is directly proportional to the number of nodes in the tree. In addition, the algorithm uses recursive function calls, which take up additional space on the call stack. However, this space is typically much smaller than the space required to store the values of the nodes, so it can be ignored for the purposes of this analysis.

Whenever we need to traverse a binary tree in full it is likely that either a recursive or iterative approach would work. In the iterative solution, a `while`

loop is used to traverse the tree and find the left edge and the right edge of the tree. A stack combined with another `while`

loop is also used to find the leaves of the tree, which is used in a similar manner to the call stack in the recursive implementation. The stack allows the leaves to be traversed while maintaining the order from left to right.

Overall, both the iterative and recursive solutions to this problem have their advantages and disadvantages, and the best approach will depend on the specific requirements and constraints of the problem at hand.

```
class Solution:
def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
# get left boundary
left_boundary = []
curr = root.left
while curr:
if curr.left is not None or curr.right is not None:
left_boundary.append(curr.val)
if curr.left:
curr = curr.left
elif curr.right:
curr = curr.right
else:
break
# get right boundary
right_boundary = []
curr = root.right
while curr:
if curr.left is not None or curr.right is not None:
right_boundary.append(curr.val)
if curr.right:
curr = curr.right
elif curr.left:
curr = curr.left
else:
break
right_boundary = right_boundary[::-1]
# get leaves
leaves = []
stack = [root]
while stack:
curr = stack.pop()
if curr != root and not curr.left and not curr.right:
leaves.append(curr.val)
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
return [root.val] + left_boundary + leaves + right_boundary
```

```
1class Solution:
2 def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
3 # get left boundary
4 left_boundary = []
5 curr = root.left
6 while curr:
7 if curr.left is not None or curr.right is not None:
8 left_boundary.append(curr.val)
9
10 if curr.left:
11 curr = curr.left
12 elif curr.right:
13 curr = curr.right
14 else:
15 break
16
17 # get right boundary
18 right_boundary = []
19 curr = root.right
20 while curr:
21 if curr.left is not None or curr.right is not None:
22 right_boundary.append(curr.val)
23
24 if curr.right:
25 curr = curr.right
26 elif curr.left:
27 curr = curr.left
28 else:
29 break
30
31 right_boundary = right_boundary[::-1]
32
33 # get leaves
34 leaves = []
35 stack = [root]
36 while stack:
37 curr = stack.pop()
38 if curr != root and not curr.left and not curr.right:
39 leaves.append(curr.val)
40
41 if curr.right:
42 stack.append(curr.right)
43 if curr.left:
44 stack.append(curr.left)
45
46 return [root.val] + left_boundary + leaves + right_boundary
47
```

- Time complexity:
`O(n)`

, as each node in the tree is visited exactly once in each of the three while loops, resulting in a total of three iterations of the tree. Since each of these operations is performed in linear time, the overall time complexity is O(n). - Space complexity:
`O(n)`

, as we created three separate arrays to store the values of the left boundary, right boundary, and leaves of the binary tree. These arrays each have a worst-case size proportional to the number of nodes in the tree, so the total space required is`O(n)`

.

Watch Mock Interviews Featuring the Boundary of Binary Tree Question

interviewing.io is a mock interview platform, and people in our community routinely share their interview replays to help others get better. In the video below, you can watch people solve Merge Linked Lists in Order. The interview is in Python. The interviewer is a senior engineer from LinkedIn.

Microsoft InterviewPython Interview

Advance this person to the next round?

Technical Skills:

4/4

Problem Solving Ability:

4/4

Communication Ability:

4/4

Show Transcript

interviewing.io is a **mock interview practice platform**. We've hosted over 100K mock interviews, conducted by senior engineers from FAANG & other top companies. We've drawn on data from these interviews to bring you the best interview prep resource on the web.

Interview prep and job hunting are chaos and pain. We can help. Really.