Boundary of Binary Tree
Explore how to identify and return the boundary of a binary tree by understanding its components: root, left boundary, leaves, and right boundary. Learn recursive techniques to traverse each boundary and apply them in coding interviews.
We'll cover the following...
We'll cover the following...
Description
Let’s start by defining what a boundary of a binary tree is. We can define it as:
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. Take a look at the example given below:
Take a look at the example given below:
As mentioned above, the boundary can be divided into four categories; the following explains these categories:
-
Root node
-
Left boundary
- The
rootnode’s left child is in the left boundary. If therootdoes not have a left child, the left boundary is empty. - If a node in the left boundary has a left child, the left child is in the left boundary.
- If a node in the left boundary has a right child but no left child, the right child is in the left boundary.
- The leftmost leaf is not in the left boundary.
- The
-
Right boundary
- The right boundary is similar to the left boundary, except it is on the right side of the
root's right subtree. - The leaf is not part of the right boundary.
- The right boundary is empty if the
rootdoes not have a right child.
- The right boundary is similar to the left boundary, except it is on the right side of the
-
Leaves
- The leaves are nodes that do not have any children. For this problem, we can assume that the
rootis not a leaf.
- The leaves are nodes that do not have any children. For this problem, we can assume that the
Considering the definition of the boundary ...