从上往下打印出二叉树的每个节点,同层节点从左至右打印。
广度优先遍历
import java.util.ArrayList; import java.util.Stack; import java.util.ArrayDeque; /** 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> intList=new ArrayList<Integer>(); if(root==null){ return intList; } ArrayDeque<TreeNode> deque = new ArrayDeque<TreeNode>(); deque.add(root); while(!deque.isEmpty()){ TreeNode rnode = deque.remove(); intList.add(rnode.val); if(rnode.left!=null){ deque.add(rnode.left); } if(rnode.right!=null){ deque.add(rnode.right); } } return intList; } }