Description:
Given an n-ary tree, return the postorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its postorder traversal as: [5,6,3,2,4,1].
Note: Recursive solution is trivial, could you do it iteratively?
题意:给定一颗N叉树,要求返回后序遍历的节点值;
解法一(递归):我们可以很容易的想到用递归来解决树的遍历问题;对于每一个节点,我们依次访问他们的每一个子节点,对于每一个子节点,再递归的遍历自己的子节点;
Java
/*
// 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> result = new LinkedList<>();
if (root == null) return result;
for (int i = 0; i < root.children.size(); i++) {
postorder(root.children.get(i), result);
}
result.addLast(root.val);
return result;
}
private void postorder(Node root, LinkedList<Integer> result) {
if (root.children.size() == 0) {
result.addLast(root.val);
return;
}
for (int i = 0; i < root.children.size(); i++) {
postorder(root.children.get(i), result);
}
result.add(root.val);
}
}
解法二(非递归):如果要利用非递归来解决这个问题的话,我们需要借助一个栈来存储子节点,对于每一个节点,我们将其所有的子节点都入栈;每一次,我们都从栈中取出一个节点,将其插入到list的首部(因为栈是后进先出的,所有第一个子节点是先入栈最后出栈的);
Java
/*
// 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> result = new LinkedList<>();
Stack<Node> treeNode = new Stack<>();
if (root == null) return result;
treeNode.push(root);
while (!treeNode.isEmpty()) {
Node temp = treeNode.pop();
result.addFirst(temp.val);
for (Node node : temp.children) {
treeNode.push(node);
}
}
return result;
}
}