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

Commitf1feae8

Browse files
Binary Tree Level Order Traversal II
1 parent6755383 commitf1feae8

File tree

1 file changed

+58
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp