题目
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
思路(自己):
- 这个题前几天做个一个类似的,也是每日一题的,比这道难多了。记得是在这道题的基础之上的;
- 理解:我咋不记得前几天我是怎么理解的了,这个输入root是要咋理解???(我想起来了,不要看题目实例给出的输入,按照Node给出的形式理解输入值就行)
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> postorder(Node root) {
if(root.children==null){
list.add(root.val);
}
else {
for(Node n:root.children){
postorder(n);
}
}
return list;
}
}
- 不知道这样为什么输出为空白(知道了,判断rooot.children不行,如果后面没有同行节点,就为Null了)
- 后序遍历为什么?先从左至右遍历子树,再输出根节点
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> postorder(Node root) {
if(root==null) return list;
if(root.children!=null){
for(Node n:root.children){
postorder(n);
}
}
if(root==null) return list;
list.add(root.val);
return list;
}
}
- 第一次提交出错是因为没有提前判断root是否为Null,导致第二个示例的时候root不存在,更不用说他的children了
- 这个时大牛写的代码,简洁明了啊
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> postorder(Node root) {
dfs(root);
return ans;
}
void dfs(Node root) {
if (root == null) return;
for (Node node : root.children) dfs(node);
ans.add(root.val);
}
}
- 以上是通过递归实现的,还有一种方法就是自建栈输出(目前还不理解!)