简单题重拳出击 还是看了题解 太久没搞树了 忘了 无语 和前序遍历一样
java:
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> res = new ArrayList<>();
goodnight(root, res);
return res;
}
public void goodnight(Node root, List<Integer> res){
if(root == null){
return ;
}
res.add(root.val);
for(Node num : root.children){
goodnight(num, res);
}
}
}
python3:
class Solution:
def preorder(self, root: 'Node') -> List[int]:
res = []
def goodnight(node : 'Node'):
if root is None:
return
res.append(node.val)
for num in node.children:
goodnight(num)
goodnight(root)
return res