Last active
May 1, 2018 14:13
-
-
Save Kyungpyo-Kim/b55e899b51be4b2a85d14f1dc607de1e to your computer and use it in GitHub Desktop.
Algorithm, Binary tree searching, Iterative preorder traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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