二叉树“之”字型遍历
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
思路:使用两个栈来实现,先将根节点入栈s1,借用层序遍历的思想,将根节点弹出栈s1时,将该节点的孩子存入另一给栈s2中。
注意,后续入栈时,s1是先将右孩子入栈,再将左孩子入栈,这样才能保证从s1弹出时是正序的。
/* 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>> res; if(pRoot==NULL) return res; TreeNode* root; stack<TreeNode *> s1; stack<TreeNode *> s2; s1.push(pRoot); while(!s1.empty()||!s2.empty()){ vector<int> temp; while(!s1.empty()){ root=s1.top(); s1.pop(); if(root->val) temp.push_back(root->val); if(root->left) s2.push(root->left); if(root->right) s2.push(root->right); } if(temp.size()){ res.push_back(temp); temp.clear(); } while(!s2.empty()){ root=s2.top(); s2.pop(); if(root->val) temp.push_back(root->val); if(root->right) s1.push(root->right); if(root->left) s1.push(root->left); } if(temp.size()){ res.push_back(temp); } } return res; } };