题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
if (pRoot == NULL)
return {};
vector<vector<int>> myTwoVec;
list<TreeNode*> mylist;
mylist.push_back(pRoot);
int mode = 0; // 0: left to right, 1: right to left
while (!mylist.empty()) {
int n = mylist.size();
vector<int> myVect{};
for (int i = 0; i < n; i++) {
TreeNode* frt;
switch (mode) {
case 0:
frt = mylist.front();
mylist.pop_front();
if (frt->left)
mylist.push_back(frt->left);
if (frt->right)
mylist.push_back(frt->right);
break;
default:
frt = mylist.back();
mylist.pop_back();
if (frt->right)
mylist.push_front(frt->right);
if (frt->left)
mylist.push_front(frt->left);
break;
}
myVect.push_back(frt->val);
}
mode = mode ? 0 : 1;
myTwoVec.push_back(myVect);
}
return myTwoVec;
}
};
美的集团公司福利 727人发布