Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //DFS recursive solution
- //Time: O(n), 3ms
- //Space: O(h)
- class Solution {
- public List<Integer> preorder(Node root) {
- List<Integer> ans = new ArrayList<>();
- DFS(root, ans);
- return ans;
- }
- private void DFS(Node root, List<Integer> ans) {
- if(root == null) return;
- ans.add(root.val);
- for(Node child : root.children) {
- DFS(child, ans);
- }
- }
- }
- /*
- // 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;
- }
- };
- */
Add Comment
Please, Sign In to add comment