Created
May 2, 2018 14:14
-
-
Save Kyungpyo-Kim/99e5775379c4e64a68ecd3c48eaa32ed to your computer and use it in GitHub Desktop.
Binary Tree Inorder 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> inorderTraversal(TreeNode* root) { | |
vector<int> out; | |
vector<TreeNode*> nodes; | |
TreeNode* node; | |
if (root != NULL) | |
node = root; | |
while(node != NULL) | |
{ | |
if(node->left != NULL) | |
{ | |
TreeNode* node_no_left = new TreeNode(node->val); | |
if (node->right != NULL) | |
node_no_left->right = node->right; | |
nodes.push_back(node_no_left); | |
nodes.push_back(node->left); | |
} | |
else | |
{ | |
out.push_back(node->val); | |
if(node->right != NULL) | |
{ | |
nodes.push_back(node->right); | |
} | |
} | |
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