Skip to content

Instantly share code, notes, and snippets.

@Kyungpyo-Kim
Last active May 1, 2018 14:13
Show Gist options
  • Save Kyungpyo-Kim/b55e899b51be4b2a85d14f1dc607de1e to your computer and use it in GitHub Desktop.
Save Kyungpyo-Kim/b55e899b51be4b2a85d14f1dc607de1e to your computer and use it in GitHub Desktop.
Algorithm, Binary tree searching, Iterative preorder traversal
/**
* Definition for a binary tree node.
* 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) {
vector<int> out;
vector<TreeNode*> nodes;
TreeNode* node = root;
while(1)
{
if (node != NULL) out.push_back(node->val);
else return out;
if (node->right != NULL) nodes.push_back(node->right);
if (node->left != NULL) nodes.push_back(node->left);
if (nodes.empty()) return out;
else
{
node = nodes.back();
nodes.pop_back();
}
}
return out;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment