Question:
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?
Solution (C++):
/**
* 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> preorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> result;
if (root == NULL) return result;
stack<TreeNode*> sta;
TreeNode *temp = NULL;
sta.push(root);
while (!sta.empty())
{
temp = sta.top();
result.push_back(temp -> val);
sta.pop();
if (temp -> right != NULL)
{
sta.push(temp -> right);
}
if(temp -> left != NULL)
{
sta.push(temp -> left);
}
}
return result;
}
};