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?
/**
* 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> results;
vector<int> preorderTraversal(TreeNode *root) {
if(root == NULL) return results;
stack<TreeNode *> st;
while(root != NULL) {
results.push_back(root->val);
st.push(root);
root = root->left;
}
while(!st.empty()) {
TreeNode *top = st.top();
st.pop();
if(top->right != NULL) {
TreeNode* temp = top->right;
results.push_back(temp->val);
st.push(temp);
temp = temp->left;
while(temp != NULL) {
results.push_back(temp->val);
st.push(temp);
temp = temp->left;
}
}
}
return results;
}
};