牛客網-劍指offer-22-從上往下列印二叉樹
從上往下打印出二叉樹的每個節點,同層節點從左至右列印。
二叉樹層序遍歷
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root==null) {
return list;
}
Queue<TreeNode> unvisited = new LinkedList<TreeNode>();
unvisited.add(root);
while(!unvisited.isEmpty()) {
TreeNode temp = unvisited.poll();
list.add(temp.val);
if(temp.left!=null) {
unvisited.add(temp.left);
}
if(temp.right!=null) {
unvisited.add(temp.right);
}
}
return list;
}
}