Given a binary tree,return the preorder traversal of its nodes’ values.
For example:
given a binary tree (1,#,2,3);
class Solution {
public:
vector<int> recursive(TreeNode* root, vector<int>& ivec){
if(!root) return ivec;
ivec.push_back(root->val);
recursive(root->left,ivec);
recursive(root->right,ivec);
return ivec;
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> ivec;
recursive(root,ivec);
return ivec;
}
};
Note: Recursive solution is trivial,could you do is it iteratively?
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>ivec;
if(!root){
return ivec;
}
stack<TreeNode*>tStack;
tStack.push(root);
TreeNode* current;
while(!tStack.empty()) {
current = tStack.top();
tStack.pop();
ivec.push_back(current->val);
if(current->right != NULL){
tStack.push(current->right);
}
if(current->left != NULL){
tStack.push(current->left);
}
}
return ivec;
}
};