Skip to content

Commit 6c0a5e3

Browse files
authored
Update 589. N-ary Tree Preorder Traversal
1 parent 0414e05 commit 6c0a5e3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Tree/589. N-ary Tree Preorder Traversal

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,63 @@ public:
4040
};
4141

4242
//https://www.youtube.com/watch?v=3E6myDNC49I
43+
44+
45+
46+
//-----------------------------------------------------itr sol
47+
48+
49+
/*
50+
// Definition for a Node.
51+
class Node {
52+
public:
53+
int val;
54+
vector<Node*> children;
55+
56+
Node() {}
57+
58+
Node(int _val) {
59+
val = _val;
60+
}
61+
62+
Node(int _val, vector<Node*> _children) {
63+
val = _val;
64+
children = _children;
65+
}
66+
};
67+
*/
68+
69+
class Solution {
70+
public:
71+
vector<int> preorder(Node* root) {
72+
73+
vector<int> result ;
74+
stack<Node*> stk ;
75+
76+
if(root == NULL)
77+
{
78+
return result ;
79+
}
80+
81+
stk.push(root); // start by pushing the root node
82+
83+
while(!stk.empty()) // loop till stack becomes empty
84+
{
85+
Node* curr = stk.top();
86+
stk.pop() ; // pop the top node
87+
result.push_back(curr->val) ; // and insert it into result
88+
89+
// loop from all children from right to left & push them into stack
90+
for(auto it = curr->children.rbegin() ; it != curr->children.rend() ; ++it )
91+
{
92+
stk.push(*it);
93+
}
94+
}
95+
96+
return result ;
97+
}
98+
};
99+
100+
101+
102+
// [3,2,4] to psuh into stack using rbegin() like 4 2 3 to pop 3 at first this preorder

0 commit comments

Comments
 (0)