Diagonal Traversal of a Binary tree
Pattern: Views and boundaries
Diagonals run down through right children; a left child starts the next diagonal. Use a queue of diagonal starts: for each start, walk its right chain, recording nodes and queueing their left children.
The problem
Return the diagonal traversal: lines of slope -1 through the tree, from the top-right one down, each read from top to
bottom. Right children stay on their parent's diagonal and left children start the next one. The example gives
[8, 10, 14, 3, 6, 7, 13, 1, 4]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Which child stays on the same diagonal?
- Where does the next diagonal begin?
- In what order should the next diagonal's starts be taken?
Hints
Brute force, and why it fails
Record each node's diagonal number (left steps) with a depth-first walk and group: also O(n).
The key insight
Walking right chains and queueing left children visits each diagonal completely before the next.
Dry run
| out | 8 10 14 |
|---|
Tree [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]. Diagonal 0: 8, 10, 14 (right chain from 8). Queue the left children 3 and 13.
The plan
queue = [root]
while queue: repeat size times: n = pop front
while n: record n; if n.left: push n.left; n = n.right
Complexity
- Time
O(n)- Space
O(n)
Each node is recorded once.
Edge cases
- A right-only chain: one diagonal.
- A left-only chain: one node per diagonal.
- Empty tree.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> diagonal(TreeNode root) {
List<Integer> out = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>(); // starts of the next diagonal
if (root != null) q.add(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
for (TreeNode n = q.poll(); n != null; n = n.right) { // a diagonal runs down right children
out.add(n.val);
if (n.left != null) q.add(n.left); // a left child starts the next diagonal
}
}
}
return out;
}
}C++
class Solution {
public:
vector<int> diagonal(TreeNode* root) {
vector<int> out;
queue<TreeNode*> q; // starts of the next diagonal
if (root != NULL) q.push(root);
while (!q.empty()) {
int size = static_cast<int>(q.size());
for (int i = 0; i < size; i++) {
TreeNode* n = q.front();
q.pop();
for (; n != NULL; n = n->right) { // a diagonal runs down right children
out.push_back(n->val);
if (n->left != NULL) q.push(n->left); // a left child starts the next diagonal
}
}
}
return out;
}
};Python
from collections import deque
class Solution:
def diagonal(self, root) -> list[int]:
out, q = [], deque([root] if root else []) # starts of the next diagonal
while q:
for _ in range(len(q)):
n = q.popleft()
while n: # a diagonal runs down right children
out.append(n.val)
if n.left:
q.append(n.left) # a left child starts the next diagonal
n = n.right
return outCommon mistakes
- Treating left children as part of the same diagonal.
- Using a stack, which reverses the order of starts.