Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6755383

Browse files
binary tree level order traversal
1 parent3a2a095 commit6755383

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
packageeasy;
2+
3+
importclasses.TreeNode;
4+
5+
importjava.util.ArrayList;
6+
importjava.util.LinkedList;
7+
importjava.util.List;
8+
importjava.util.Queue;
9+
10+
/**102. Binary Tree Level Order Traversal
11+
12+
Total Accepted: 117221
13+
Total Submissions: 341219
14+
Difficulty: Easy
15+
16+
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
17+
18+
For example:
19+
Given binary tree [3,9,20,null,null,15,7],
20+
21+
3
22+
/ \
23+
9 20
24+
/ \
25+
15 7
26+
27+
return its level order traversal as:
28+
29+
[
30+
[3],
31+
[9,20],
32+
[15,7]
33+
]
34+
*/
35+
publicclassBinaryTreeLevelOrderTraversal {
36+
//Cheers, easily made it AC'ed on the first submission now, practice does make perfect!
37+
publicList<List<Integer>>levelOrder(TreeNoderoot) {
38+
List<List<Integer>>result =newArrayList<List<Integer>>();
39+
if(root ==null)returnresult;
40+
41+
Queue<TreeNode>q =newLinkedList<TreeNode>();
42+
q.offer(root);
43+
while(!q.isEmpty()){
44+
List<Integer>thisLevel =newArrayList<Integer>();
45+
intqSize =q.size();
46+
for(inti =0;i <qSize;i++){
47+
TreeNodecurr =q.poll();
48+
thisLevel.add(curr.val);
49+
if(curr.left !=null)q.offer(curr.left);
50+
if(curr.right !=null)q.offer(curr.right);
51+
}
52+
result.add(thisLevel);
53+
}
54+
returnresult;
55+
}
56+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp