從上往下打印出二叉樹的每一個節點,同層節點從左至右打印。java
按層次打印二叉樹的節點,重點就是咱們在打印一層節點的時候,同時按順序保存好當前節點的下一層節點,也就是左節點和右節點,當此層節點打印完畢後,再打印剛纔保存好的節點序列,也就是廣度優先遍歷。咱們可使用兩個數組分別用來保存打印層節點,和下一層節點,在當前層結束後,將下層數組賦給打印數組,循環執行,知道打印數組爲空,也就打印完畢了。數組
也可使用隊列來打印二叉樹,每打印一個節點,就將這個節點的左右節點添加進隊列中,直到隊列爲空。this
C++spa
class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { if(root == nullptr) return res; vector<TreeNode*> TNode; vector<TreeNode*> temp; TNode.push_back(root); while(!TNode.empty()){ for(int i = 0; i < TNode.size(); ++i){ res.push_back(TNode[i]->val); if(TNode[i]->left) temp.push_back(TNode[i]->left); if(TNode[i]->right) temp.push_back(TNode[i]->right); } TNode.swap(temp); temp.clear(); } return res; } private: vector<int> res; };
Javacode
import java.util.ArrayList; import java.util.Queue; 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) { if(root == null) return res; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode n = queue.poll(); res.add(n.val); if(n.left != null) queue.offer(n.left); if(n.right != null) queue.offer(n.right); } return res; } private ArrayList<Integer> res = new ArrayList<>(); }