Level-order Traversal of Binary Trees
Given the root of a binary tree, return its nodes' values in level order from left to right.
Constraints:
- Node count: 0–2000
- Node value range: -1000 to 1000
Approach: Perform breadth-first traversal using a queue. Collect nodes of each depth into a separate list before proceeidng to the next level.
class TreeNode {
int data;
TreeNode leftChild;
TreeNode rightChild;
TreeNode() {}
TreeNode(int val) { data = val; }
TreeNode(int val, TreeNode l, TreeNode r) {
data = val;
leftChild = l;
rightChild = r;
}
}
public class Solution {
public java.util.List<java.util.List<Integer>> traverseByLevel(TreeNode root) {
java.util.List<java.util.List<Integer>> result = new java.util.ArrayList<>();
if (root == null) return result;
java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
java.util.List<Integer> currentLayer = new java.util.ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode curr = queue.poll();
currentLayer.add(curr.data);
if (curr.leftChild != null) queue.add(curr.leftChild);
if (curr.rightChild != null) queue.add(curr.rightChild);
}
result.add(currentLayer);
}
return result;
}
}
Inverting a Binary Tree
Given the root of a binary tree, invert it so that left and right children of all nodes are swaped, and return the new root.
Constraints:
- Node count: 0–100
- Node value range: -100 to 100
Approach: Use breadth-first traversal to visit each node and swap its two children.
public class Solution {
public TreeNode mirrorTree(TreeNode root) {
if (root == null) return null;
java.util.Deque<TreeNode> stack = new java.util.ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
exchangeChildren(node);
if (node.leftChild != null) stack.push(node.leftChild);
if (node.rightChild != null) stack.push(node.rightChild);
}
return root;
}
private void exchangeChildren(TreeNode n) {
TreeNode tmp = n.leftChild;
n.leftChild = n.rightChild;
n.rightChild = tmp;
}
}
Checking Symmetry in a Binary Tree
Determine weather a binary tree is symmetric around its center.
Constraints:
- Node count: 1–1000
- Node value range: -100 to 100
Approach: Use iterative level-order traversal comparing mirrored positions. Enqueue pairs of nodes that should match in value and presence.
public class Solution {
public boolean isMirror(TreeNode root) {
if (root == null) return true;
java.util.Queue<TreeNode> q = new java.util.LinkedList<>();
q.offer(root.leftChild);
q.offer(root.rightChild);
while (!q.isEmpty()) {
TreeNode leftNode = q.poll();
TreeNode rightNode = q.poll();
if (leftNode == null && rightNode == null) continue;
if (leftNode == null || rightNode == null) return false;
if (leftNode.data != rightNode.data) return false;
q.offer(leftNode.leftChild);
q.offer(rightNode.rightChild);
q.offer(leftNode.rightChild);
q.offer(rightNode.leftChild);
}
return true;
}
}