N-ary Tree Postorder Traversal
Last updated
Last updated
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
LinkedList<Node> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
Node node = stack.pop();
res.addFirst(node.val);
if (node.children != null) {
for (Node c: node.children) {
if (c != null) {
stack.push(c);
}
}
}
}
return res;
}
}class Solution {
public List<Integer> postorder(Node root) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
postorderHelper(root, res);
return res;
}
private void postorderHelper(Node root, List<Integer> res) {
if (root == null) {
return;
}
if (root.children != null) {
for (Node c : root.children) {
postorderHelper(c, res);
}
}
res.add(root.val);
}
}