cswork / templatesOpen the Line 500 list

STOP 10 · LISTS & TREES

Binary Tree Traversal and Structure

Level-order BFS O(n) time · O(width) space

Contest ratings Rating 1676–Rating 1703· median Rating 1690(2 of 26 problems rated by zerotrac)

Open the Line 500 list · stop 10 · 26 problems
Learn first
Leads to
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 TraversalEasy
Stuck? Peek at the approach

Use preorder traversal to connect recursive execution with an explicit stack.

Key points

  1. Record the queue length at the start of each round; processing exactly that many nodes separates one level from the next.
  2. Before writing a recursive DFS, decide what a subtree returns (depth, balance, size); the answer is always a merge of left and right.
  3. 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.

Interactive demo · step by step

Tree traversal · stack and queue

Walk the tree in preorder, inorder, postorder, level order

Try your own input
ABCDEFG
CurrentDiscovered / computedAnswer
Stack bottom → top, or queue front → back
Empty
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 levels
C++
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) >= 0
C++
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

  1. 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.
  2. 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)。
English
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.

Key points you covered (0 of 2)
How well did you know it?

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

5 questions
  1. Recursive DFS on a binary tree with n nodes and height h uses how much extra (call stack) space?
  2. A full binary tree (every node has 0 or 2 children) has n internal nodes. How many leaves does it have?
  3. To compute every subtree's height bottom-up, a node must come after both of its subtrees. Which DFS order is that?
  4. The tree has n nodes and height h. What are the time and extra space?
    def height(node):
        if not node:
            return 0
        return 1 + max(height(node.left), height(node.right))
  5. balanced(root) runs on a perfectly balanced binary tree with n nodes. What is the time complexity?
    def height(node):
        if not node:
            return 0
        return 1 + max(height(node.left), height(node.right))
    
    def balanced(node):
        if not node:
            return True
        if abs(height(node.left) - height(node.right)) > 1:
            return False
        return balanced(node.left) and balanced(node.right)

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 levels

Practice 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

#ProblemApproachRating
144Binary Tree Preorder TraversalUse preorder traversal to connect recursive execution with an explicit stack.
94Binary Tree Inorder TraversalPractice inorder traversal by pushing down the left spine and returning through ancestors.
145Binary Tree Postorder TraversalUse postorder traversal to understand why subtrees must be processed before their parent.
104Maximum Depth of Binary TreeCompute tree height through recursive return values and distinguish counting nodes from counting edges.
111Minimum Depth of Binary TreeCompute minimum depth correctly when a node has only one nonempty subtree.
100Same TreeTraverse two trees together to compare both structure and node values.
101Symmetric TreeExpress symmetry as paired recursion over mirrored positions.
226Invert Binary TreeSwap left and right subtrees recursively to understand in-place structural changes.
617Merge Two Binary TreesWhen merging trees, distinguish shared positions from branches that exist on only one side.
404Sum of Left LeavesRecognize left leaves through parent-child relationships without counting ordinary left children.
102Binary Tree Level Order TraversalMaintain queue boundaries by level as a foundation for level-order traversal variants.
107Binary Tree Level Order Traversal IIReorganize level-order results without confusing node order with level order.

Core 10

#ProblemApproachRating
103Binary Tree Zigzag Level Order TraversalAlternate the output direction by level, separating traversal order from presentation order.
199Binary Tree Right Side ViewExtract the right view from each level's last node or from right-first DFS.
513Find Bottom Left Tree ValueFind the leftmost node on the deepest level by maintaining traversal order and depth state.
110Balanced Binary TreeCompute height and balance together from the bottom up to avoid repeated traversal.
543Diameter of Binary TreeDistinguish the single-branch height returned to a parent from the diameter passing through the current node.
572Subtree of Another TreeSeparate the recursive tasks of locating candidate roots and comparing complete subtrees.
116Populating Next Right Pointers in Each NodeUse the structure of a perfect binary tree to connect next pointers across each level.
222Count Complete Tree NodesUse the left and right boundary heights of a complete binary tree to accelerate node counting.
958Check Completeness of a Binary TreeValidate completeness by checking which nodes can appear after a gap in level-order traversal.Rating 1703
314Binary Tree Vertical Order Traversal 🔒Collect nodes by column and use BFS to preserve top-to-bottom order and within-level order naturally.

Advanced 4

#ProblemApproachRating
117Populating Next Right Pointers in Each Node IIBuild the next-level chain in an arbitrary binary tree, connecting across missing subtrees.
662Maximum Width of Binary TreeAssign relative positional indices to compute tree width while controlling index growth.
987Vertical Order Traversal of a Binary TreeApply ordering by column, row, and value, handling multiple nodes at the same coordinates.Rating 1676
545Boundary of Binary Tree 🔒Separate the boundary into the left edge, leaves, and reversed right edge without counting nodes twice.