题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解:
层次遍历
/*
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)
return result;
TreeNode* pCur = NULL;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
pCur = q.front();
q.pop();
result.push_back(pCur->val);
if(pCur->left)
q.push(pCur->left);
if(pCur->right)
q.push(pCur->right);
}
return result;
}
};