Given a binary tree, return the preorder traversal of its nodes' values.
// non-recursion version:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> solution;
// recursive is easy
// let's do it without recursive
// probably need to use stack
vector<int> preorderTraversal(TreeNode *root) {
if (root==NULL)
return solution;
stack<TreeNode *> mystack;
TreeNode * node;
mystack.push(root);
while (!mystack.empty()){
node = mystack.top();
mystack.pop();
if (node){
solution.push_back(node->val);
mystack.push(node->right);
mystack.push(node->left);
}
}
return solution;
}
};