Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given the root
of an n-ary tree, return the postorder traversal of its nodes’ values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
Constraints:
[0, 104]
.0 <= Node.val <= 104
1000
.class Solution {
public List<Integer> postorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.add(root);
while(!stack.isEmpty()) {
root = stack.pop();
list.add(root.val);
for(Node node: root.children)
stack.add(node);
}
Collections.reverse(list);
return list;
}
}
vector<int> postorder(Node* root) {
if(root==NULL) return {};
vector<int> res;
stack<Node*> stk;
stk.push(root);
while(!stk.empty())
{
Node* temp=stk.top();
stk.pop();
for(int i=0;i<temp->children.size();i++) stk.push(temp->children[i]);
res.push_back(temp->val);
}
reverse(res.begin(), res.end());
return res;
}
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res = []
if root == None: return res
def recursion(root, res):
for child in root.children:
recursion(child, res)
res.append(root.val)
recursion(root, res)
return res
In our experience, we suggest you solve this N-ary Tree Postorder Traversal LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the N-ary Tree Postorder Traversal LeetCode Solution
I hope this N-ary Tree Postorder Traversal LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>