一:題目描述
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
二:解題思路
藉助隊列實現
在之前的一道劍指OFFER當中用到相同思想,比這道題個複雜,還要保證二叉樹每一層要換行。
三:代碼實現
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> result;
if(root==NULL)
return result;
queue<TreeNode*> pNode;
pNode.push(root);
while(!pNode.empty()){
//隊列不爲空
//隊首出隊
TreeNode* temp=pNode.front();
//保存該結點的值
result.push_back(temp->val);
//該結點出隊
pNode.pop();
if(temp->left!=NULL)
pNode.push(temp->left);
if(temp->right!=NULL)
pNode.push(temp->right);
}
return result;
}
};