Guest User

Untitled

a guest
Jul 16th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. //Recursive solution: use a seperate recursive func to count the path begin with certain root
  2. //Time: O(n), 12ms
  3. //Space: O(h)
  4. class Solution {
  5. int max = 0;//The longest univalue path length so far
  6. public int longestUnivaluePath(TreeNode root) {
  7. if(root == null) return 0;
  8. if(root.left == null && root.right == null) return 0;
  9. int ans = 0;//The longest path length that go through root
  10. longestUnivaluePath(root.left);
  11. longestUnivaluePath(root.right);
  12. if(root.left != null && root.val == root.left.val) {
  13. ans += 1 + pathBegin(root.left);
  14. }
  15. if(root.right != null && root.val == root.right.val) {
  16. ans += 1 + pathBegin(root.right);
  17. }
  18. //The longest path may go through root or may not
  19. max = Math.max(max, ans);
  20. //Return the longest univalue path after we traverse the whole tree
  21. return max;
  22. }
  23.  
  24. //Return the path length begin with root
  25. private int pathBegin(TreeNode root) {
  26. if(root.left == null && root.right == null) return 0;
  27. int left = 0, right = 0;
  28. if(root.left != null && root.val == root.left.val) {
  29. left += 1 + pathBegin(root.left);
  30. }
  31. if(root.right != null && root.val == root.right.val) {
  32. right += 1 + pathBegin(root.right);
  33. }
  34. return Math.max(left, right);
  35. }
  36. }
  37. /**
  38. * Definition for a binary tree node.
  39. * public class TreeNode {
  40. * int val;
  41. * TreeNode left;
  42. * TreeNode right;
  43. * TreeNode(int x) { val = x; }
  44. * }
  45. */
Add Comment
Please, Sign In to add comment