问题描述如下:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
问题链接cpp代码如下:
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
TreeNode *p=root;
vector<int> ans;
stack<TreeNode*> sta;
while(p||!sta.empty()){
if(p){
ans.push_back(p->val);
if(p->right)
sta.push(p->right);
p=p->left;
}else{
p=sta.top();
sta.pop();
}
}
return ans;
}
};