LeetCode687-最长同值路径

题目链接

英文链接:https://leetcode.com/problems/longest-univalue-path/

中文链接:https://leetcode-cn.com/problems/longest-univalue-path/

题目详述

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

注意:两个节点之间的路径长度由它们之间的边数表示。

示例 1:

输入:

    5
   / \
  4   5
 / \   \
1   1   5

输出:

2
示例 2:

输入:

    1
   / \
  4   5
 / \   \
4   4   5

输出:

2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

题目详解

  • 对于当前结点,左支链长度为 left,如果当前结点的值等于左孩子的值,那么加上当前结点的支链的长度为 left + 1,否则为 0。
  • 对于当前结点,右支链长度为 right,如果当前结点的值等于右孩子的值,那么加上当前结点的支链的长度为 right + 1,否则为 0。
  • 加上当前结点的支链长度为上面两者之和,用来更新全局最大值。
  • 返回值为两者较大值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class LeetCode_00687 {

public int longestUnivaluePath(TreeNode root) {
int[] res = new int[1];
dfs(root, res);
return res[0];
}

private int dfs(TreeNode root, int[] res) {
if (root == null) {
return 0;
}
int left = dfs(root.left, res);
int right = dfs(root.right, res);
left = root.left != null && root.left.val == root.val ? left + 1 : 0;
right = root.right != null && root.right.val == root.val ? right + 1 : 0;
res[0] = Math.max(res[0], left + right);
return Math.max(left, right);
}
}