STOP 10 · LISTS & TREES
Binary Tree Traversal and Structure
Level-order BFS O(n) time · O(width) space
- Learn first
- How often asked
- asked by 9 companies · in 24 reportsMeta 10, Amazon 3, LinkedIn 3, Microsoft 2, TikTok / ByteDance 2
Warm up with this one
LC 144Binary Tree Preorder TraversalStuck? Peek at the approach
Use preorder traversal to connect recursive execution with an explicit stack.
Key points
- Record the queue length at the start of each round; processing exactly that many nodes separates one level from the next.
- Before writing a recursive DFS, decide what a subtree returns (depth, balance, size); the answer is always a merge of left and right.
- Pre-, in- and post-order differ only in whether you handle the current node before, between or after the two recursive calls.
Common pitfalls
- Using the live queue length as the loop bound mixes the next level into the current one.
- list.pop(0) is O(n) in Python; use collections.deque for queues.
- A degenerate tree recurses 10^5 levels deep and overflows Python's stack; go iterative or raise the recursion limit.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Tree traversal · stack and queue
Walk the tree in preorder, inorder, postorder, level order
Try your own input
- Order
- Preorder
- Output
- —
One tree, four traversal orders. #k under a node is its position in the current output.
InvariantThe three depth-first orders differ only in where the root is output: before, between or after its subtrees. Level order uses a queue, and first in, first out means level by level.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 144, with it.
Python
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def level_order(root) -> list[list[int]]:
if not root:
return []
levels, q = [], deque([root])
while q:
level = []
for _ in range(len(q)): # exactly the nodes of this level
node = q.popleft()
level.append(node.val)
for child in (node.left, node.right):
if child:
q.append(child)
levels.append(level)
return levelsC++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> levels;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
levels.emplace_back();
for (int k = q.size(); k > 0; k--) { // exactly the nodes of this level
TreeNode* node = q.front();
q.pop();
levels.back().push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return levels;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> levels = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int k = q.size(); k > 0; k--) { // exactly the nodes of this level
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
levels.add(level);
}
return levels;
}
}Go
type TreeNode struct {
Val int
Left, Right *TreeNode
}
func levelOrder(root *TreeNode) [][]int {
var levels [][]int
var q []*TreeNode
if root != nil {
q = append(q, root)
}
for len(q) > 0 {
var level []int
var next []*TreeNode // the following level
for _, node := range q {
level = append(level, node.Val)
if node.Left != nil {
next = append(next, node.Left)
}
if node.Right != nil {
next = append(next, node.Right)
}
}
levels = append(levels, level)
q = next
}
return levels
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Postorder heights, with -1 for "already unbalanced"O(n) time · O(h) recursion depth
When a check needs facts about subtrees (balance, height, diameter), a postorder walk hands each node its children's results before it computes its own, and an impossible height such as -1 carries a failure straight up without recomputing anything. LC 110 (Balanced Binary Tree), LC 104 (Maximum Depth) and LC 543 (Diameter of Binary Tree) have this shape.
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_balanced(root) -> bool:
"""Every node's two subtree heights differ by at most 1 (LC 110)."""
def height(node) -> int: # -1 means "not balanced", passed straight up
if not node:
return 0
left = height(node.left)
if left < 0:
return -1
right = height(node.right)
if right < 0 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return height(root) >= 0C++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
// Every node's two subtree heights differ by at most 1 (LC 110).
bool isBalanced(TreeNode* root) {
function<int(TreeNode*)> height = [&](TreeNode* node) { // -1 means "not balanced", passed straight up
if (!node) return 0;
int left = height(node->left);
if (left < 0) return -1;
int right = height(node->right);
if (right < 0 || left - right > 1 || right - left > 1) return -1;
return 1 + max(left, right);
};
return height(root) >= 0;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
// Every node's two subtree heights differ by at most 1 (LC 110).
boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
// -1 means "not balanced", passed straight up.
private int height(TreeNode node) {
if (node == null) return 0;
int left = height(node.left);
if (left < 0) return -1;
int right = height(node.right);
if (right < 0 || Math.abs(left - right) > 1) return -1;
return 1 + Math.max(left, right);
}
}Go
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// isBalanced reports whether every node's two subtree heights differ by at most 1 (LC 110).
func isBalanced(root *TreeNode) bool {
var height func(node *TreeNode) int // -1 means "not balanced", passed straight up
height = func(node *TreeNode) int {
if node == nil {
return 0
}
left := height(node.Left)
if left < 0 {
return -1
}
right := height(node.Right)
if right < 0 || left-right > 1 || right-left > 1 {
return -1
}
return 1 + max(left, right)
}
return height(root) >= 0
}Iterative with a stack: preorder, and postorder by reversalO(n) time · O(h) to O(n) space
When the tree may be too deep to recurse, or the interviewer rules recursion out: preorder uses one stack, pushing the right child before the left; postorder walks root, right, left and reverses the result. The iterative inorder is at the binary search tree stop. LC 144, LC 145, LC 94.
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def preorder(root) -> list[int]:
"""Root, left, right without recursion (LC 144)."""
res, stack = [], [root] if root else []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right) # pushed first, so it comes out after the left subtree
if node.left:
stack.append(node.left)
return res
def postorder(root) -> list[int]:
"""Left, right, root: a root, right, left walk reversed (LC 145)."""
res, stack = [], [root] if root else []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]C++
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};
// Root, left, right without recursion (LC 144).
vector<int> preorder(TreeNode* root) {
vector<int> res;
vector<TreeNode*> stack;
if (root) stack.push_back(root);
while (!stack.empty()) {
TreeNode* node = stack.back();
stack.pop_back();
res.push_back(node->val);
if (node->right) stack.push_back(node->right); // pushed first, so it comes out after the left subtree
if (node->left) stack.push_back(node->left);
}
return res;
}
// Left, right, root: a root, right, left walk reversed (LC 145).
vector<int> postorder(TreeNode* root) {
vector<int> res;
vector<TreeNode*> stack;
if (root) stack.push_back(root);
while (!stack.empty()) {
TreeNode* node = stack.back();
stack.pop_back();
res.push_back(node->val);
if (node->left) stack.push_back(node->left);
if (node->right) stack.push_back(node->right);
}
reverse(res.begin(), res.end());
return res;
}Java
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
// Root, left, right without recursion (LC 144).
List<Integer> preorder(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
res.add(node.val);
if (node.right != null) stack.push(node.right); // pushed first, so it comes out after the left subtree
if (node.left != null) stack.push(node.left);
}
return res;
}
// Left, right, root: a root, right, left walk reversed (LC 145).
List<Integer> postorder(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
res.add(node.val);
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
Collections.reverse(res);
return res;
}
}Go
type TreeNode struct {
Val int
Left, Right *TreeNode
}
// preorder walks root, left, right without recursion (LC 144).
func preorder(root *TreeNode) []int {
var res []int
var stack []*TreeNode
if root != nil {
stack = append(stack, root)
}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, node.Val)
if node.Right != nil {
stack = append(stack, node.Right) // pushed first, so it comes out after the left subtree
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return res
}
// postorder walks left, right, root: a root, right, left walk reversed (LC 145).
func postorder(root *TreeNode) []int {
var res []int
var stack []*TreeNode
if root != nil {
stack = append(stack, root)
}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, node.Val)
if node.Left != nil {
stack = append(stack, node.Left)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
}
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}Why it works
- At the start of each round the queue holds exactly one whole level: round 0 has just the root, and after processing that level's size nodes, what was enqueued is exactly their children, the next level. By induction, levels never mix.
- Recursive DFS is correct by structural induction: assume both subtrees return correct values; if the node merges them correctly, the whole tree is correct, with the empty tree as the base case.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
层序遍历我用队列,每一轮开始先记下队列长度,正好处理这么多个节点,这样一层和下一层不会混在一起:处理完这一层,队列里剩下的恰好是下一层。如果是 DFS,我先定义子树要返回什么,比如高度或是否平衡,再用左右子树的结果合并出当前节点,正确性靠结构归纳。每个节点访问一次,O(n)。For level order I use a queue and record its length at the start of each round, then process exactly that many nodes, so one level never mixes with the next. After a round, the queue holds exactly the following level. For DFS, I first define what a subtree returns, such as its height or whether it is balanced, then combine the left and right results at the node, which is correct by structural induction. Every node is visited once, so it is O(n).Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
levels.append(level)
return levelsPractice by stage
This stop's 26 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 12
| # | Problem | Approach | Rating |
|---|---|---|---|
| 144 | Binary Tree Preorder Traversal | Use preorder traversal to connect recursive execution with an explicit stack. | |
| 94 | Binary Tree Inorder Traversal | Practice inorder traversal by pushing down the left spine and returning through ancestors. | |
| 145 | Binary Tree Postorder Traversal | Use postorder traversal to understand why subtrees must be processed before their parent. | |
| 104 | Maximum Depth of Binary Tree | Compute tree height through recursive return values and distinguish counting nodes from counting edges. | |
| 111 | Minimum Depth of Binary Tree | Compute minimum depth correctly when a node has only one nonempty subtree. | |
| 100 | Same Tree | Traverse two trees together to compare both structure and node values. | |
| 101 | Symmetric Tree | Express symmetry as paired recursion over mirrored positions. | |
| 226 | Invert Binary Tree | Swap left and right subtrees recursively to understand in-place structural changes. | |
| 617 | Merge Two Binary Trees | When merging trees, distinguish shared positions from branches that exist on only one side. | |
| 404 | Sum of Left Leaves | Recognize left leaves through parent-child relationships without counting ordinary left children. | |
| 102 | Binary Tree Level Order Traversal | Maintain queue boundaries by level as a foundation for level-order traversal variants. | |
| 107 | Binary Tree Level Order Traversal II | Reorganize level-order results without confusing node order with level order. |
Core 10
| # | Problem | Approach | Rating |
|---|---|---|---|
| 103 | Binary Tree Zigzag Level Order Traversal | Alternate the output direction by level, separating traversal order from presentation order. | |
| 199 | Binary Tree Right Side View | Extract the right view from each level's last node or from right-first DFS. | |
| 513 | Find Bottom Left Tree Value | Find the leftmost node on the deepest level by maintaining traversal order and depth state. | |
| 110 | Balanced Binary Tree | Compute height and balance together from the bottom up to avoid repeated traversal. | |
| 543 | Diameter of Binary Tree | Distinguish the single-branch height returned to a parent from the diameter passing through the current node. | |
| 572 | Subtree of Another Tree | Separate the recursive tasks of locating candidate roots and comparing complete subtrees. | |
| 116 | Populating Next Right Pointers in Each Node | Use the structure of a perfect binary tree to connect next pointers across each level. | |
| 222 | Count Complete Tree Nodes | Use the left and right boundary heights of a complete binary tree to accelerate node counting. | |
| 958 | Check Completeness of a Binary Tree | Validate completeness by checking which nodes can appear after a gap in level-order traversal. | |
| 314 | Binary Tree Vertical Order Traversal 🔒 | Collect nodes by column and use BFS to preserve top-to-bottom order and within-level order naturally. |
Advanced 4
| # | Problem | Approach | Rating |
|---|---|---|---|
| 117 | Populating Next Right Pointers in Each Node II | Build the next-level chain in an arbitrary binary tree, connecting across missing subtrees. | |
| 662 | Maximum Width of Binary Tree | Assign relative positional indices to compute tree width while controlling index growth. | |
| 987 | Vertical Order Traversal of a Binary Tree | Apply ordering by column, row, and value, handling multiple nodes at the same coordinates. | |
| 545 | Boundary of Binary Tree 🔒 | Separate the boundary into the left edge, leaves, and reversed right edge without counting nodes twice. |
OA questions on this topic 9
- Nested List Weight Sum (for E4)Meta
- Sewer Drainage PartitionTwo Sigma
- Maximum Time Required to Transfer DataRippling
- Rooted Distances (Re-rooting DP)MathWorks
- Chain of Command (Tree DFS Order, k-th Receiver)IMC
- Tree PointsThe D. E. Shaw Group
- Count Balanced Nodes in a TreeDeloitte
- Minimum Flips to Match Expected Binary Values in a TreeUkg
- Build MonumentsOther