Last active
May 19, 2022 19:47
-
-
Save Earu/c9351d4c47784257d9bb47dc80158237 to your computer and use it in GitHub Desktop.
Tree: Preorder Traversal challenge on hackerrank.com
This file contains hidden or 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
#include <bits/stdc++.h> | |
#include <stack> | |
using namespace std; | |
class Node { | |
public: | |
int data; | |
Node *left; | |
Node *right; | |
Node(int d) | |
{ | |
data = d; | |
left = NULL; | |
right = NULL; | |
} | |
}; | |
class Solution { | |
public: | |
Node* insert(Node* root, int data) | |
{ | |
if(root == NULL) | |
{ | |
return new Node(data); | |
} | |
else | |
{ | |
Node* cur; | |
if(data <= root->data) | |
{ | |
cur = insert(root->left, data); | |
root->left = cur; | |
} | |
else | |
{ | |
cur = insert(root->right, data); | |
root->right = cur; | |
} | |
return root; | |
} | |
} | |
/* you only have to complete the function given below. | |
Node is defined as | |
class Node { | |
public: | |
int data; | |
Node *left; | |
Node *right; | |
Node(int d) { | |
data = d; | |
left = NULL; | |
right = NULL; | |
} | |
}; | |
*/ | |
void preOrder(Node *root) | |
{ | |
unordered_set<Node*> metNodes; | |
stack<Node*> nodeStack; | |
Node* node = root; | |
nodeStack.push(root); | |
while (!nodeStack.empty()) | |
{ | |
if (metNodes.find(node) == metNodes.end()) | |
{ | |
metNodes.insert(node); | |
cout << node->data << " "; | |
} | |
if (node->left != nullptr && metNodes.find(node->left) == metNodes.end()) | |
{ | |
nodeStack.push(node); | |
node = node->left; | |
} | |
else if (node->right != nullptr && metNodes.find(node->right) == metNodes.end()) | |
{ | |
nodeStack.push(node); | |
node = node->right; | |
} | |
else | |
{ | |
Node* previous = nodeStack.top(); | |
nodeStack.pop(); | |
node = previous; | |
} | |
} | |
} | |
}; //End of Solution | |
int main() | |
{ | |
Solution myTree; | |
Node* root = NULL; | |
int t; | |
int data; | |
std::cin >> t; | |
while(t-- > 0) | |
{ | |
std::cin >> data; | |
root = myTree.insert(root, data); | |
} | |
myTree.preOrder(root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment