从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
总觉得这题在LeetCode上面做过,待优化。
/*
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) {
//BFS
stack<TreeNode*> st1,st2,st3;
vector<int> res{};
if(!root) return res;
st1.push(root);
while((!st1.empty())||(!st2.empty())){
if(st1.empty()){
while(!(st2.empty())){
TreeNode *cur=st2.top();
st2.pop();
res.push_back(cur->val);
st3.push(cur);//st3辅助栈,逆序
// if(cur->right) st1.push(cur->right);
// if(cur->left) st1.push(cur->left);
}
while(!(st3.empty())){
TreeNode *cur=st3.top();
st3.pop();
if(cur->right) st1.push(cur->right);
if(cur->left) st1.push(cur->left);
}
}
else{
while(!(st1.empty())){
TreeNode *cur=st1.top();
st1.pop();
res.push_back(cur->val);
if(cur->right) st2.push(cur->right);
if(cur->left) st2.push(cur->left);
}
}
}
return res;
}
};