Binary Trees Depth first: return a value up
354. Boundary of Binary Tree
You are given root, the root node of a binary tree. Return the values on its boundary, in this order: the
root, then the left boundary from the top down, then every leaf from left to right, then the right boundary
from the bottom up. This goes once around the outside of the tree, counterclockwise.
A leaf is a node with no children. The root is never a leaf, even when it has no children, so a tree of one node gives just its root.
The left boundary starts at the root's left child and walks down. From each node it steps to the left child, or to the right child when there is no left child. It stops when it reaches a leaf and does not include that leaf, because the leaf is listed with the other leaves. If the root has no left child, the left boundary is empty. The right boundary is the mirror image. It starts at the root's right child, steps to the right child, or to the left child when there is no right child, and does not include the leaf where it stops. If the root has no right child, it is empty. Each node appears in the answer at most once.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [1, 2, 3, null, 4, 5, 6, 7, 8, 10, 11, 9]
[1,2,4,7,8,10,11,9,6,3]Explanation: The left boundary is 2, then 4, because 2 has no left child; it stops at the leaf 7. The leaves are 7, 8, 10, 11 and 9. The right boundary is 3, then 6, and since 6 has no right child it steps to 9, a leaf. Bottom up, it is 6, 3. Node 5 is on none of these, so it is not listed.
Example 2
Input: root = [-10, null, -20, 30, -40]
[-10,30,-40,-20]Explanation: The root has no left child, so the left boundary is empty. 30 is listed once, as a leaf, then −40, and the right boundary is just −20.
Example 3
Input: root = [7]
[7]Explanation: The root is not a leaf, so it is listed once.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.