Skip to content

Commit ad218f7

Browse files
authored
Merge pull request gzc426#339 from heyheyheyi/master
1
2 parents 10795ff + 7b4ed6d commit ad218f7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

2018.12.05-leetcode102/棕榈树.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
```

0 commit comments

Comments
 (0)