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> vecNode;
stack<TreeNode* > sNode;
TreeNode* temp = root;
while (0 != temp || !sNode.empty())
{
if (0 != temp)
{
vecNode.push_back(temp->val);
if (0 != temp->right)
sNode.push(temp->right);
temp = temp->left;
}
else
{
temp = sNode.top();
sNode.pop();
}
}
return vecNode;
}
};