c++ 栈和队列
求二叉树的前序遍历
http://www.nowcoder.com/questionTerminal/501fb3ca49bb4474bf5fa87274e884b4
class Solution {
public:
/*
*
* @param root TreeNode类
* @return int整型vector
*/
vector<int> preorderTraversal(TreeNode</int> root) {
// write code here
vector<int> res;
if (root==NULL)
return res;
queue<TreeNode> q;
stack<TreeNode> s;
q.push(root);
while (!s.empty()||!q.empty()){
TreeNode* tmp = NULL;
if (!q.empty()){
tmp = q.front();
q.pop();
}
else{
tmp = s.top();
s.pop();
}
res.push_back(tmp->val);
if (tmp->left!=NULL)
q.push(tmp->left);
if (tmp->right!=NULL)
s.push(tmp->right);
}
return res;
}
};</int>