劍指offer之 從上往下打印二叉樹
阿新 • • 發佈:2017-10-13
節點 result ava null val imp tree solution 當前
import java.util.ArrayList; import java.util.LinkedList; /** 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) { //定義一個輔助隊列 LinkedList<TreeNode> queue=new LinkedList<>(); //存儲一層的打印結果 ArrayList<Integer> resultCur=new ArrayList<Integer>(); if(root==null){ return resultCur; } //定義兩個變量last和nlast,分別記錄當前行的最右節點和下一行的最右節點 TreeNode last=root; TreeNode nlast=root; TreeNode cur=root; queue.add(root); while(queue.size()!=0){ cur=queue.poll(); resultCur.add(cur.val); if(cur.left!=null){ queue.add(cur.left); nlast=cur.left; } if(cur.right!=null){ queue.add(cur.right); nlast=cur.right; } if(cur==last){ last=nlast; } } return resultCur; } }
劍指offer之 從上往下打印二叉樹