-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path102-BinaryTreeLevelOrderTraversal.java
45 lines (39 loc) · 1.12 KB
/
102-BinaryTreeLevelOrderTraversal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//Question Link - https://leetcode.com/problems/binary-tree-level-order-traversal/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//bfs traversal technique
List<List<Integer>> res = new ArrayList<>();
bfs(res, root, 0);
return res;
}
public void bfs(List<List<Integer>> ans, TreeNode root, int h) {
//base case
if (root == null) {
return;
}
else {
//if the height becomes greater, it means we have entered new level
if(h >= ans.size()) {
ans.add(new ArrayList<>());
}
ans.get(h).add(root.val);
bfs(ans, root.left, h+1);
bfs(ans, root.right, h+1);
}
}
}