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].
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?
使用迭代(非递归)的方法遍历二叉树。
可以使用stack或者list记录遍历的回退路径,实现前序遍历。
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> vec;
if(root==NULL)
return vec;
stack<TreeNode*> s;
s.push(root);
TreeNode *current;
while(!s.empty()){
current = s.top();
s.pop();
if(current){
vec.push_back(current->val);
s.push(current->right);
s.push(current->left);
}
}
return vec;
}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> vec;
if(root==NULL)
return vec;
list<TreeNode*> L;
L.push_back(root);
TreeNode *current;
while(!L.empty()){
current = L.front();
L.pop_front();
if(current){
vec.push_back(current->val);
L.push_front(current->right);
L.push_front(current->left);
}
}
return vec;
}
};