|
| 1 | +--- |
| 2 | +id: level-order-traversal |
| 3 | +title: Level Order Traversal |
| 4 | +sidebar_label: Level Order Traversal |
| 5 | +tags: |
| 6 | +- Tree |
| 7 | +- Breadth-First Search |
| 8 | +- Binary Tree |
| 9 | +description: "This is a solution to the Binary Tree Level Order Traversal problem on LeetCode." |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem Description |
| 13 | +Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). |
| 14 | + |
| 15 | +### Examples |
| 16 | + |
| 17 | +**Example 1:** |
| 18 | + |
| 19 | +``` |
| 20 | +Input: root = [3,9,20,null,null,15,7] |
| 21 | +Output: [[3],[9,20],[15,7]] |
| 22 | +``` |
| 23 | + |
| 24 | +**Example 2:** |
| 25 | +``` |
| 26 | +Input: root = [1] |
| 27 | +Output: [[1]] |
| 28 | +``` |
| 29 | + |
| 30 | + |
| 31 | +### Constraints |
| 32 | +- The number of nodes in the tree is in the range [0, 2000]. |
| 33 | +- `-1000 <= Node.val <= 1000` |
| 34 | + |
| 35 | +## Solution for Binary Tree Level Order Traversal |
| 36 | + |
| 37 | +### Intuition |
| 38 | +- To perform a level-order traversal on a binary tree and store the nodes’ values in a 2D vector representing each level, start by initialising an empty queue to hold the level by level nodes.Enqueue the root node into the queue and traverse until the queue is empty. For each level, track the number of nodes in that level, creating a temporary vector to deque and store them. At each node, store its value in the temporary vector and enqueue its left and right children if they exist.Once all the nodes at a level are processed add this 1D temporary vector to the final 2D vector, representing that level. This process repeats until all levels are traversed. Finally, return this 2D vector containing the level order traversal of the binary tree. |
| 39 | +<Tabs> |
| 40 | + <TabItem value="Solution" label="Solution"> |
| 41 | +#### Implementation |
| 42 | + |
| 43 | +```jsx live |
| 44 | +function Solution() { |
| 45 | +function TreeNode(val = 0, left = null, right = null) { |
| 46 | + this.val = val; |
| 47 | + this.left = left; |
| 48 | + this.right = right; |
| 49 | +} |
| 50 | +function constructTreeFromArray(array) { |
| 51 | + if (!array.length) return null; |
| 52 | + |
| 53 | + let root = new TreeNode(array[0]); |
| 54 | + let queue = [root]; |
| 55 | + let i = 1; |
| 56 | + |
| 57 | + while (i < array.length) { |
| 58 | + let currentNode = queue.shift(); |
| 59 | + |
| 60 | + if (array[i] !== null) { |
| 61 | + currentNode.left = new TreeNode(array[i]); |
| 62 | + queue.push(currentNode.left); |
| 63 | + } |
| 64 | + i++; |
| 65 | + |
| 66 | + if (i < array.length && array[i] !== null) { |
| 67 | + currentNode.right = new TreeNode(array[i]); |
| 68 | + queue.push(currentNode.right); |
| 69 | + } |
| 70 | + i++; |
| 71 | + } |
| 72 | + return root; |
| 73 | +} |
| 74 | +function levelOrder(root) { |
| 75 | + if (!root) return []; |
| 76 | + |
| 77 | + const queue = [root]; |
| 78 | + const ans = []; |
| 79 | + |
| 80 | + while (queue.length > 0) { |
| 81 | + const size = queue.length; |
| 82 | + const temp = []; |
| 83 | + |
| 84 | + for (let i = 0; i < size; i++) { |
| 85 | + const curr = queue.shift(); |
| 86 | + |
| 87 | + if (curr.left) queue.push(curr.left); |
| 88 | + if (curr.right) queue.push(curr.right); |
| 89 | + |
| 90 | + temp.push(curr.val); |
| 91 | + } |
| 92 | + |
| 93 | + ans.push(temp); |
| 94 | + } |
| 95 | + |
| 96 | + return ans; |
| 97 | +} |
| 98 | + |
| 99 | + |
| 100 | +const array = [3,9,20,null,null,15,7] |
| 101 | +const input = constructTreeFromArray(array) |
| 102 | +const output = levelOrder(input) |
| 103 | + return ( |
| 104 | + <div> |
| 105 | + <p> |
| 106 | + <b>Input: </b>{JSON.stringify(array)} |
| 107 | + </p> |
| 108 | + <p> |
| 109 | + <b>Output:</b> {output.toString()} |
| 110 | + </p> |
| 111 | + </div> |
| 112 | + ); |
| 113 | +} |
| 114 | +``` |
| 115 | + |
| 116 | +### Code in Different Languages |
| 117 | + |
| 118 | +<Tabs> |
| 119 | + <TabItem value="JavaScript" label="JavaScript"> |
| 120 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 121 | + ```javascript |
| 122 | + } |
| 123 | +function levelOrder(root) { |
| 124 | + if (!root) return []; |
| 125 | + |
| 126 | + const queue = [root]; |
| 127 | + const ans = []; |
| 128 | + |
| 129 | + while (queue.length > 0) { |
| 130 | + const size = queue.length; |
| 131 | + const temp = []; |
| 132 | + |
| 133 | + for (let i = 0; i < size; i++) { |
| 134 | + const curr = queue.shift(); |
| 135 | + |
| 136 | + if (curr.left) queue.push(curr.left); |
| 137 | + if (curr.right) queue.push(curr.right); |
| 138 | + |
| 139 | + temp.push(curr.val); |
| 140 | + } |
| 141 | + |
| 142 | + ans.push(temp); |
| 143 | + } |
| 144 | + |
| 145 | + return ans; |
| 146 | +} |
| 147 | +``` |
| 148 | + </TabItem> |
| 149 | + <TabItem value="TypeScript" label="TypeScript"> |
| 150 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 151 | + ```typescript |
| 152 | + class TreeNode { |
| 153 | + val: number; |
| 154 | + left: TreeNode | null; |
| 155 | + right: TreeNode | null; |
| 156 | + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 157 | + this.val = (val === undefined ? 0 : val); |
| 158 | + this.left = (left === undefined ? null : left); |
| 159 | + this.right = (right === undefined ? null : right); |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +function levelOrder(root: TreeNode | null): number[][] { |
| 164 | + if (!root) return []; |
| 165 | + |
| 166 | + const queue: TreeNode[] = [root]; |
| 167 | + const ans: number[][] = []; |
| 168 | + |
| 169 | + while (queue.length > 0) { |
| 170 | + const size = queue.length; |
| 171 | + const temp: number[] = []; |
| 172 | + |
| 173 | + for (let i = 0; i < size; i++) { |
| 174 | + const curr = queue.shift()!; |
| 175 | + |
| 176 | + if (curr.left) queue.push(curr.left); |
| 177 | + if (curr.right) queue.push(curr.right); |
| 178 | + |
| 179 | + temp.push(curr.val); |
| 180 | + } |
| 181 | + |
| 182 | + ans.push(temp); |
| 183 | + } |
| 184 | + |
| 185 | + return ans; |
| 186 | +} |
| 187 | + ``` |
| 188 | + </TabItem> |
| 189 | + <TabItem value="Python" label="Python"> |
| 190 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 191 | + ```python |
| 192 | +from collections import deque |
| 193 | +class TreeNode: |
| 194 | + def __init__(self, val=0, left=None, right=None): |
| 195 | + self.val = val |
| 196 | + self.left = left |
| 197 | + self.right = right |
| 198 | + |
| 199 | +class Solution: |
| 200 | + def levelOrder(self, root: TreeNode) -> List[List[int]]: |
| 201 | + if not root: |
| 202 | + return [] |
| 203 | + |
| 204 | + q = deque([root]) |
| 205 | + ans = [] |
| 206 | + |
| 207 | + while q: |
| 208 | + size = len(q) |
| 209 | + temp = [] |
| 210 | + |
| 211 | + for _ in range(size): |
| 212 | + curr = q.popleft() |
| 213 | + |
| 214 | + if curr.left: |
| 215 | + q.append(curr.left) |
| 216 | + if curr.right: |
| 217 | + q.append(curr.right) |
| 218 | + |
| 219 | + temp.append(curr.val) |
| 220 | + |
| 221 | + ans.append(temp) |
| 222 | + |
| 223 | + return ans |
| 224 | + ``` |
| 225 | + </TabItem> |
| 226 | + <TabItem value="Java" label="Java"> |
| 227 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 228 | +```java |
| 229 | +import java.util.*; |
| 230 | + |
| 231 | +class TreeNode { |
| 232 | + int val; |
| 233 | + TreeNode left; |
| 234 | + TreeNode right; |
| 235 | + TreeNode(int x) { val = x; } |
| 236 | +} |
| 237 | + |
| 238 | +class Solution { |
| 239 | + public List<List<Integer>> levelOrder(TreeNode root) { |
| 240 | + Queue<TreeNode> q = new LinkedList<>(); |
| 241 | + List<List<Integer>> ans = new ArrayList<>(); |
| 242 | + |
| 243 | + if (root == null) return ans; |
| 244 | + |
| 245 | + q.offer(root); |
| 246 | + |
| 247 | + while (!q.isEmpty()) { |
| 248 | + int size = q.size(); |
| 249 | + List<Integer> temp = new ArrayList<>(); |
| 250 | + |
| 251 | + for (int i = 0; i < size; i++) { |
| 252 | + TreeNode curr = q.poll(); |
| 253 | + |
| 254 | + if (curr.left != null) q.offer(curr.left); |
| 255 | + if (curr.right != null) q.offer(curr.right); |
| 256 | + |
| 257 | + temp.add(curr.val); |
| 258 | + } |
| 259 | + |
| 260 | + ans.add(temp); |
| 261 | + } |
| 262 | + |
| 263 | + return ans; |
| 264 | + } |
| 265 | +} |
| 266 | + |
| 267 | +``` |
| 268 | +</TabItem> |
| 269 | + <TabItem value="C++" label="C++"> |
| 270 | + <SolutionAuthor name="@hiteshgahanolia"/> |
| 271 | +```cpp |
| 272 | +class Solution { |
| 273 | +public: |
| 274 | + vector<vector<int>> levelOrder(TreeNode* root) { |
| 275 | + queue<TreeNode *> q; |
| 276 | + vector<vector<int>> ans; |
| 277 | + |
| 278 | + if(!root) return ans; |
| 279 | + |
| 280 | + q.push(root); |
| 281 | + |
| 282 | + while(!q.empty()){ |
| 283 | + int size = q.size(); |
| 284 | + vector<int> temp; |
| 285 | + |
| 286 | + while(size--){ |
| 287 | + TreeNode *curr = q.front(); |
| 288 | + q.pop(); |
| 289 | + |
| 290 | + if(curr->left) q.push(curr->left); |
| 291 | + if(curr->right) q.push(curr->right); |
| 292 | + |
| 293 | + temp.push_back(curr->val); |
| 294 | + } |
| 295 | + |
| 296 | + ans.push_back(temp); |
| 297 | + } |
| 298 | + |
| 299 | + return ans; |
| 300 | + } |
| 301 | +}; |
| 302 | +``` |
| 303 | + </TabItem> |
| 304 | + </Tabs> |
| 305 | +
|
| 306 | +#### Complexity Analysis |
| 307 | + ##### Time Complexity: |
| 308 | + - $O(N)$ where N is the number of nodes in the binary tree. Each node of the binary tree is enqueued and dequeued exactly once, hence all nodes need to be processed and visited. Processing each node takes constant time operations which contributes to the overall linear time complexity. |
| 309 | +
|
| 310 | + ##### Space Complexity: |
| 311 | + - $O(N)$ where N is the number of nodes in the binary tree. In the worst case, the queue has to hold all the nodes of the last level of the binary tree, the last level could at most hold N/2 nodes hence the space complexity of the queue is proportional to $O(N)$.The resultant vector answer also stores the values of the nodes level by level and hence contains all the nodes of the tree contributing to O(N) space as well. |
| 312 | +
|
| 313 | +</TabItem> |
| 314 | +</Tabs> |
| 315 | +
|
| 316 | +## References |
| 317 | +
|
| 318 | +- **LeetCode Problem**: [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |
| 319 | +
|
| 320 | +- **Solution Link**: [LeetCode Solution](hhttps://leetcode.com/problems/binary-tree-level-order-traversal/solutions) |
| 321 | +
|
0 commit comments