题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) { vector<vector<int> > ret; if (pRoot == nullptr) return ret; deque<TreeNode*> s; s.push_back(pRoot); int level = 0; while (!s.empty()) { int size = s.size(); vector<int> tmp; while (size--) { if (level % 2 == 0) { TreeNode* p = s.back(); s.pop_back(); tmp.push_back(p->val); if (p->left) s.push_front(p->left); if (p->right) s.push_front(p->right); } else { TreeNode* p = s.front(); s.pop_front(); tmp.push_back(p->val); if(p->right) s.push_back(p->right); if(p->left) s.push_back(p->left); } } ret.push_back(tmp); level++; } return ret; } };
也可以改变每层打印顺序,用vector的insert()方法