-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbstlevelorder.java
More file actions
78 lines (63 loc) · 1.65 KB
/
Copy pathbstlevelorder.java
File metadata and controls
78 lines (63 loc) · 1.65 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*Binary Tree Level Order Traversal
Solved
Given a binary tree root, return the level order traversal of it as a nested list, where each sublist contains the values of nodes at a particular level in the tree, from left to right.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [[1],[2,3],[4,5,6,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
0 <= The number of nodes in both trees <= 1000.
-1000 <= Node.val <= 1000
*/
/**
* 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) {
List<List<Integer>> list = new ArrayList<>();
int h=height(root);
for(int i=1;i<=h;i++)
{
List<Integer> levellist = new ArrayList<>();
bfs(root,i,levellist);
list.add(levellist);
}
return list;
}
int height(TreeNode root)
{
if(root!=null)
{
return 1 + Math.max(height(root.left),height(root.right));
}
return 0;
}
void bfs(TreeNode root,int level,List<Integer>levellist)
{
if(root==null) return ;
if(level==1)
{
levellist.add(root.val);
}
bfs(root.left,level-1,levellist);
bfs(root.right,level-1,levellist);
}
}
//Time complexcity=O(n);