Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- // Definition for a Node.
- class Node {
- public:
- int val;
- vector<Node*> children;
- Node() {}
- Node(int _val) {
- val = _val;
- }
- Node(int _val, vector<Node*> _children) {
- val = _val;
- children = _children;
- }
- };
- */
- class Solution {
- public:
- vector<int> preorder(Node* root) {
- stack<Node*> Stack;
- // 'Preorder'-> contains all the
- // visited nodes
- vector<int> Preorder;
- if(root==nullptr)
- {
- return Preorder;
- }
- Stack.push(root);
- while (!Stack.empty()) {
- Node* temp = Stack.top();
- Stack.pop();
- // store the key in preorder vector(visited list)
- Preorder.push_back(temp->val);
- // Push all of the child nodes of temp into
- // the stack from right to left.
- for (int i = temp->children.size() - 1; i >= 0; i--) {
- Stack.push(temp->children[i]);
- }
- }
- return Preorder;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment