Guest User

Untitled

a guest
Jul 15th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. //Recursive 1-pass in-order traversal solution: save the ans in an ArrayList first
  2. //Time: O(n), 2ms
  3. //Space: O(n), when input is 1,2,3,4,...,n-2,n-1,n-1
  4. class Solution {
  5. int currVal;
  6. int currCount = 0;
  7. int maxCount = 0;
  8.  
  9. public int[] findMode(TreeNode root) {
  10. ArrayList<Integer> list = new ArrayList<>();
  11. DFS(root, list);
  12. int[] ans = new int[list.size()];
  13. for(int i = 0; i < ans.length; i++) {
  14. ans[i] = list.get(i);
  15. }
  16. return ans;
  17. }
  18.  
  19. private void DFS(TreeNode root, ArrayList<Integer> list) {
  20. if(root == null) return;
  21. DFS(root.left, list);
  22. handleValue(root.val, list);
  23. DFS(root.right, list);
  24. }
  25.  
  26. private void handleValue(int val, ArrayList<Integer> list) {
  27. if(val != currVal) {
  28. currVal = val;
  29. currCount = 0;
  30. }
  31. currCount++;
  32. if(currCount > maxCount) {
  33. list.clear();
  34. list.add(val);
  35. maxCount = currCount;
  36. } else if(currCount == maxCount) {
  37. list.add(val);
  38. }
  39. }
  40. }
  41. /**
  42. * Definition for a binary tree node.
  43. * public class TreeNode {
  44. * int val;
  45. * TreeNode left;
  46. * TreeNode right;
  47. * TreeNode(int x) { val = x; }
  48. * }
  49. */
Add Comment
Please, Sign In to add comment