题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
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> res;
if(root==NULL)
return res;
deque<TreeNode*> dequeTreeNode;
dequeTreeNode.push_back(root);
while(dequeTreeNode.size()) //循环终止条件:队列元素全部打印为空
{
TreeNode* pNode= dequeTreeNode.front(); //返回双端队列dequeTreeNode的首元素给pNode
dequeTreeNode.pop_front(); //删除双端队列dequeTreeNode的首元素
res.push_back(pNode->val); //将此时的dequeTreeNode第一个元素存入到输出容器res中
if(pNode->left) //若当前结点的左结点不为空,将其左结点存入到双端队列dequeTreeNode中
dequeTreeNode.push_back(pNode->left);
if(pNode->right)
dequeTreeNode.push_back(pNode->right); 若当前结点的右结点不为空,将其右结点存入到双端队列dequeTreeNode中
}
return res;
}
};