从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
可以利用图的BFS的思想,借助一个双端队列deque.
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> rst;
if(root==NULL)
return rst;
deque<TreeNode*> temp;
temp.push_back(root);
while(temp.size()!=0){
TreeNode* t=temp.front();
temp.pop_front();
rst.push_back(t->val);
if(t->left!=NULL)
temp.push_back(t->left);
if(t->right!=NULL)
temp.push_back(t->right);
}
return rst;
}
};