Created
May 2, 2018 15:40
-
-
Save Kyungpyo-Kim/c95f452eb777c120c84fac1b5c82aa52 to your computer and use it in GitHub Desktop.
Binary Tree Postorder 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> postorderTraversal(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 | |
{ | |
if(node->right != NULL) | |
{ | |
TreeNode* node_no_left = new TreeNode(node->val); | |
nodes.push_back(node_no_left); | |
nodes.push_back(node->right); | |
} | |
else | |
{ | |
out.push_back(node->val); | |
} | |
} | |
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