-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution.java
More file actions
47 lines (41 loc) · 1.01 KB
/
Copy pathSolution.java
File metadata and controls
47 lines (41 loc) · 1.01 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
package com.algorithdemo.tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* 题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
*
*/
public class Solution {
public static void printFromTopToBottom(TreeNode root) {
if(root == null){
return;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode last = root;
TreeNode nLast = null;
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
System.out.print(root.getValue() + " ");
if(root.getLeft() != null){
queue.offer(root.getLeft());
nLast = root.getLeft();
}
if(root.getRight() != null){
queue.offer(root.getRight());
nLast = root.getRight();
}
if(root == last && !queue.isEmpty()){
last = nLast;
}
}
}
public static void main(String[] args) {
TreeNode tree = new TreeNode(1);
TreeNode lt = new TreeNode(2);
TreeNode rt = new TreeNode(3);
tree.setLeft(lt);
tree.setRight(rt);
printFromTopToBottom(tree);
}
}