https://leetcode-cn.com/problems/longest-univalue-path/

二叉树的递归套路

  • 与x无关

    左右子树的max去pk一下

  • 与x有关

    • 1)x自己
    • 2)x 连同左树
    • 3)x 连同右树
    • 4)x连同左树和右树
  1. public int longestUnivaluePath(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. return process(root).max - 1;
  6. }
  7. public class Info {
  8. public int len; // 路径必须以x为开头且只能往下走的情况下,路径的最大距离
  9. public int max; // 路径不要求必须从x出发的情况下,整棵树的合法路径的最大距离
  10. public Info(int l, int m) {
  11. len = l;
  12. max = m;
  13. }
  14. }
  15. private Info process(TreeNode x) {
  16. if (x == null) {
  17. return new Info(0, 0);
  18. }
  19. TreeNode l = x.left;
  20. TreeNode r = x.right;
  21. Info lInfo = process(l);
  22. Info rInfo = process(r);
  23. // x自己
  24. int len = 1;
  25. if (l != null && x.val == l.val) {
  26. len = lInfo.len + 1;
  27. }
  28. if (r != null && x.val == r.val) {
  29. len = Math.max(len, rInfo.len + 1);
  30. }
  31. // 这一句代码就把5种情况pk了一下
  32. int max = Math.max(Math.max(lInfo.max, rInfo.max), len);
  33. if (l != null && r != null && x.val == l.val && x.val == r.val) {
  34. max = Math.max(max, lInfo.len + rInfo.len + 1);
  35. }
  36. return new Info(len, max);
  37. }