题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分类:二叉树
解法1:使用队列来进行层次遍历即可。
[java]
view plain
copy
import java.util.ArrayList; public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> res = new ArrayList<Integer>(); if(root==null) return res; ArrayList<TreeNode> queue = new ArrayList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ TreeNode cur = queue.remove(0); res.add(cur.val); if(cur.left!=null){ queue.add(cur.left); } if(cur.right!=null){ queue.add(cur.right); } } return res; } }
原文链接 http://blog.csdn.net/crazy__chen/article/details/44998621