标签:pre ++ int res style 输出 auto add new
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
层次打印二叉树,在打印二叉树结点的同时,保存好结点的左右孩子,不断的重复打印,直到需要打印的数组为空即可。
C++
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { if(pRoot == nullptr) return res; vector<TreeNode*> printS; vector<TreeNode*> temp; printS.push_back(pRoot); while(!printS.empty()){ //vector<TreeNode*> temp; vector<int> resTemp; for(auto i:printS){ if(i->left != nullptr) temp.push_back(i->left); if(i->right != nullptr) temp.push_back(i->right); } for(int i = 0; i < printS.size(); ++i) resTemp.push_back(printS[i]->val); res.push_back(resTemp); printS.swap(temp); temp.clear(); } return res; } private: vector<vector<int>> res; };
Java
import java.util.ArrayList; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { if(pRoot == null) return res; ArrayList<TreeNode> printS = new ArrayList<>(); ArrayList<TreeNode> temp = new ArrayList<>(); printS.add(pRoot); while(!printS.isEmpty()){ ArrayList<Integer> resTemp = new ArrayList<>(); for(TreeNode i:printS){ if(i.left != null) temp.add(i.left); if(i.right != null) temp.add(i.right); } for(int i = 0; i < printS.size(); ++i) resTemp.add(printS.get(i).val); res.add(resTemp); printS.clear(); printS.addAll(temp); temp.clear(); resTemp = null; } return res; } private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); }
剑指Offer-60.把二叉树打印成多行(C++/Java)
标签:pre ++ int res style 输出 auto add new
原文地址:https://www.cnblogs.com/silentteller/p/12115190.html