/*
// Definition for a Node.
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;
}
};
*/
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> ans = new ArrayList<>();
dfs(root, ans);
return ans;
}
private void dfs(Node node, List<Integer> ans) {
if (node == null) {
return;
}
ans.add(node.val);
for (Node c : node.children) {
dfs(c, ans);
}
}
}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
func preorder(root *Node) (ans []int) {
var dfs func(*Node)
dfs = func(node *Node) {
if node == nil {
return
}
ans = append(ans, node.Val)
for _, c := range node.Children {
dfs(c)
}
}
dfs(root)
return
}
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
ans = []
def dfs(node: 'Node'):
if node is None:
return
ans.append(node.val)
for ch in node.children:
dfs(ch)
dfs(root)
return ans
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
if not root.children:
return [root.val]
result = [root.val]
for child in root.children:
result += self.preorder(child)
return result
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return [];
if not root.children:
return [root.val];
result = [root.val];
for child in root.children:
result += self.preorder(child);
return result;