#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
public:
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
vector<vector<int>> Print(TreeNode* pRoot){
vector<vector<int>> res;
if(pRoot == nullptr)
return res;
stack<TreeNode*> s0, s1; // s0, left->right,; s1: right->left
s0.push(pRoot);
while(!s0.empty() || !s1.empty()){
vector<int> vv;
if(!s0.empty()){
while(!s0.empty()){
TreeNode* tmp = s0.top();
s0.pop();
vv.push_back(tmp->val);
if(tmp->left !=nullptr){
s1.push(tmp->left);
}
if(tmp->right !=nullptr){
s1.push(tmp->right);
}
}
res.push_back(vv);
}
else if(!s1.empty()){ // if - else if is important, it means only one of condition is satisfied
while(!s1.empty()){
TreeNode* tmp = s1.top();
s1.pop();
vv.push_back(tmp->val);
if(tmp->right != nullptr){
s0.push(tmp->right);
}
if(tmp->left !=nullptr){
s0.push(tmp->left);
}
}
res.push_back(vv);
}
}
return res;
}
z字形遍历二叉树
最新推荐文章于 2022-06-02 17:02:39 发布