Перейти к содержимому

Binary Tree Level Order Traversal in Java | BFS Queue | Java Interview Prep: Advanced #08

Code & Test Automation

0:00 / 0:00

Binary Tree Level Order Traversal in Java | BFS Queue | Java Interview Prep: Advanced #08

1 просмотр · 2 дн. назад
Code & Test Automation
16 подписчиков
1 просмотр · 2 дн. назад
Code & Test Automation |    / @codetestautomation   Learn binary tree level order traversal in Java with a breadth-first search queue, one of the most common tree questions in coding interviews! In this lesson we cover the contract (one list of values per depth, a null root returns an empty list), a picture of the tree level by level, the simple idea of collecting each depth separately that costs O(n times h), the plan from the guide (a queue, capture the size before each level, enqueue non-null children left before right), the Java code line by line with ArrayDeque, a full dry run of [3,9,20,null,null,15,7] (answer [[3], [9, 20], [15, 7]]), why the captured count matters, edge cases such as a null root, a single node and a skewed chain, O(n) time and O(w) space for the maximum width w, and the follow-up: zigzag level order. Episode 8 of 20 in Java Interview Prep: Advanced (advanced windows, monotonic structures, linked lists, trees, tries, dynamic programming, weighted graphs and backtracking). CHAPTERS 0:00 Introduction 0:51 The problem 1:43 Intuition 2:19 The simple idea 3:01 The plan 3:25 The Java code 4:17 Dry run 5:26 Why count matters 6:02 Edge cases & tests 6:54 Complexity 7:25 Interview follow-up 8:11 Recap 8:33 Subscribe THE SOLUTION (Java) static class TreeNode { int value; TreeNode left, right; TreeNode(int value) { this.value = value; } } static List‹List‹Integer›› levelOrder(TreeNode root) { List‹List‹Integer›› out = new ArrayList‹›(); if (root == null) return out; Queue‹TreeNode› q = new ArrayDeque‹›(); q.offer(root); while (!q.isEmpty()) { int count = q.size(); List‹Integer› level = new ArrayList‹›(); for (int i = 0; i ‹ count; i++) { TreeNode node = q.remove(); level.add(node.value); if (node.left != null) q.offer(node.left); if (node.right != null) q.offer(node.right); } out.add(level); } return out; } Example: Tree [3,9,20,null,null,15,7] =› [[3], [9,20], [15,7]] Complexity: O(n) time; O(w) auxiliary space for maximum tree width w, excluding output. Practice tip: type it, run it, then explain it out loud: the invariant, the complexity and the edge cases. Next episode: #09 Validate a binary search tree. #Java #CodingInterview #DSA #CodeAndTestAutomation Subscribe to Code & Test Automation for more Java interview prep:    / @codetestautomation