Question
Solution
题目大意:后序遍历一个树
思路:
1)递归
2)迭代
Java实现(递归):
public Listpostorder(Node root) { List ansList = new ArrayList<>(); recursivePostorder(root, ansList); return ansList;}void recursivePostorder(Node root, List ansList) { if (root == null) return; if (root.children != null) { for (Node tmp : root.children) { recursivePostorder(tmp, ansList); } } ansList.add(root.val);}
Java实现(迭代):
public Listpostorder(Node root) { List ansList = new ArrayList<>(); if (root == null) return ansList; List nodeList = new ArrayList<>(); nodeList.add(root); while (nodeList.size() > 0) { Node cur = nodeList.get(nodeList.size() - 1); nodeList.remove(nodeList.size() - 1); ansList.add(cur.val); if (cur.children != null) { for (Node tmp : cur.children) { nodeList.add(tmp); } } } for (int i=0; i