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?
前序遍历,同样不能使用递归
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> rel;
if(root==NULL) return rel;
if(root) s.push(root);
while(!s.empty()){
TreeNode * p = s.top();
s.pop();
while(p!=NULL){
rel.push_back(p->val);
if(p->right!=NULL) s.push(p->right);
p = p->left;
}
}
return rel;
}
stack<TreeNode*> s;
};