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?
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
if(root) stk.push(root);
TreeNode*cur;
while(!stk.empty()){
cur = stk.top();
stk.pop();
res.push_back(cur->val);
if(cur->right) stk.push(cur->right);
if(cur->left) stk.push(cur->left);
}
return res;
}
};