Ctrl K

Tree Outline, Counterclockwise

Medium
You are given the root of a binary tree. Trace its outline counterclockwise starting from the root and return the node values in the order you visit them. The outline consists of four parts, one after another: 1. **The root.** 2. **The left side**: a path that starts at the root's left child. From each node on the path, move to its left child, or to its right child if there is no left one. The path stops just before the first leaf: the leaf itself is not part of the left side. If the root has no left child, the left side is empty. 3. **All leaves** of the tree from left to right. A leaf is a node with no children; the root never counts as a leaf, even when it is the only node. 4. **The right side**, in reverse order (bottom-up). It mirrors the left side: it starts at the root's right child, moves to the right child, or to the left one if there is no right child, and also stops just before a leaf. Every node appears in the answer at most once.
Example 1
root=tree_node([5, 8, 2, None, 4, 7, 9, 1, 6]) → [5, 8, 4, 1, 6, 7, 9, 2]

The root is 5. Left side: 8 (no left child, so go right to 4), then 4 (go left to 1, which is a leaf). Leaves from left to right: 1, 6, 7, 9. The right side is just 2 (next comes the leaf 9). Result: [5, 8, 4, 1, 6, 7, 9, 2].

Example 2
root=tree_node([3, None, 10, 11, None, 12]) → [3, 12, 11, 10]

There is no left subtree, so the left side is empty. The only leaf is 12. The right side from top to bottom is 10, 11, and it goes into the answer bottom-up.

Example 3
root=tree_node([42]) → [42]

A tree with only the root: the answer is just the root.

Constraints
  • 1 ≤ number of nodes ≤ 10⁴
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([5, 8, 2, None, 4, 7, 9, 1, 6])
Expected
[5, 8, 4, 1, 6, 7, 9, 2]

Run checks the first 3 tests in your browser. Submit checks all 100 tests on the server, hidden ones included.