题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
核心代码实现
import java
.util
.*
;
public class Solution {
public ArrayList
<Integer> PrintFromTopToBottom(TreeNode root
) {
ArrayList
<Integer> result
= new ArrayList<>();
Queue
<TreeNode> nodes
= new LinkedList<>();
if(root
== null
){
return result
;
}
nodes
.offer(root
);
while(!nodes
.isEmpty()){
TreeNode temp
= nodes
.poll();
result
.add(temp
.val
);
if(temp
.left
!= null
){
nodes
.offer(temp
.left
);
}
if(temp
.right
!= null
){
nodes
.offer(temp
.right
);
}
}
return result
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-14030.html