Guest User

Untitled

a guest
Jul 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. //DFS recursive solution
  2. //Time: O(n), 3ms
  3. //Space: O(h)
  4. class Solution {
  5. public List<Integer> preorder(Node root) {
  6. List<Integer> ans = new ArrayList<>();
  7. DFS(root, ans);
  8. return ans;
  9. }
  10.  
  11. private void DFS(Node root, List<Integer> ans) {
  12. if(root == null) return;
  13. ans.add(root.val);
  14. for(Node child : root.children) {
  15. DFS(child, ans);
  16. }
  17. }
  18. }
  19. /*
  20. // Definition for a Node.
  21. class Node {
  22. public int val;
  23. public List<Node> children;
  24.  
  25. public Node() {}
  26.  
  27. public Node(int _val,List<Node> _children) {
  28. val = _val;
  29. children = _children;
  30. }
  31. };
  32. */
Add Comment
Please, Sign In to add comment