Guest User

Untitled

a guest
Jan 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _687_longest_univalue_path_II
  8. {
  9. public class TreeNode
  10. {
  11. public int val;
  12. public TreeNode left;
  13. public TreeNode right;
  14. public TreeNode(int x) { val = x; }
  15. }
  16.  
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. }
  22.  
  23. /// <summary>
  24. /// Jan. 19, 2019
  25. /// The design has a problem
  26. /// </summary>
  27. /// <param name="root"></param>
  28. /// <returns></returns>
  29. public static int LongestUnivaluePath(TreeNode root) {
  30. if (root == null || (root.left == null && root.right == null))
  31. return 0;
  32.  
  33. if (root.left != null && root.val == root.left.val && root.right != null && root.val == root.right.val)
  34. {
  35. return 2 + LongestUnivaluePath(root.left) + LongestUnivaluePath(root.right);
  36. }
  37.  
  38. var left = LongestUnivaluePath(root.left);
  39. var right = LongestUnivaluePath(root.right);
  40.  
  41. if(root.left != null && root.val == root.left.val)
  42. {
  43. left++;
  44. }
  45.  
  46. if(root.right != null && root.val == root.right.val)
  47. {
  48. right++;
  49. }
  50.  
  51. return Math.Max(left, right);
  52. }
  53. }
  54. }
Add Comment
Please, Sign In to add comment