(C++)劍指offer-60:把二叉樹列印成多行(樹)
阿新 • • 發佈:2019-01-11
劍指offer-60:把二叉樹列印成多行
目錄
1題目描述
從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。
2解析及答案
層次遍歷
跟上一題一樣,將奇偶行去掉就行了
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot == NULL)
return res;
queue <TreeNode*> que;
que.push(pRoot);
while(!que.empty()){ //que非空迴圈,為空則終止迴圈
vector<int> vec;
const int size = que.size(); //每次佇列中被壓入的節點數量,1,2,4...
for(int i=0; i<size; ++i){
TreeNode* tmp = que.front(); //取出佇列的首元素
que.pop(); //彈出佇列第一個元素
vec.push_back(tmp->val); //將值壓入vec中
if(tmp->left != NULL) //先壓左孩子,再壓右孩子
que.push(tmp->left);
if(tmp->right != NULL)
que.push(tmp->right);
}
res.push_back(vec);
}
return res;
}
};