File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ ```
2
+ public class levelOrderInBinaryTree {
3
+ public class TreeNode{
4
+ int value;
5
+ TreeNode left;
6
+ TreeNode right;
7
+ public TreeNode(int value) {
8
+ this.value = value;
9
+ }
10
+ }
11
+
12
+ public List<List<Integer>> levelOrder(TreeNode root){
13
+ List<List<Integer>> list = new ArrayList<>();//存放一棵树
14
+ List<Integer> tempList = new ArrayList<>();//存放一层的值
15
+ if(root == null){
16
+ return list;
17
+ }
18
+ Queue<TreeNode> queue = new LinkedList<>();
19
+ queue.add(root);
20
+ int toBePrint = 1;//当前层要打印的节点数
21
+ int nextLevelCount = 0;//下一层要打印的节点数
22
+ while(queue.isEmpty() == false){
23
+ TreeNode temp = queue.poll();
24
+ tempList.add(temp.value);
25
+ toBePrint--;
26
+ if(temp.left!=null){
27
+ queue.add(temp.left);
28
+ nextLevelCount++;
29
+ }
30
+ if(temp.right!=null){
31
+ queue.add(temp.right);
32
+ nextLevelCount++;
33
+ }
34
+ if(toBePrint==0){ //打印完本层的节点,做善后工作
35
+ list.add(new ArrayList<>(tempList));
36
+ tempList.clear();
37
+ toBePrint = nextLevelCount;
38
+ nextLevelCount=0;
39
+ }
40
+ }
41
+ return list;
42
+ }
43
+ }
44
+ ```
You can’t perform that action at this time.
0 commit comments