687. 最长同值路径

Difficulty
Medium
Tags
二叉树
Star
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例 1:
输入:
5 / \ 4 5 / \ \ 1 1 5
输出:
2
示例 2:
输入:
1 / \ 4 5 / \ \ 4 4 5
输出:
2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。

法1 递归法

思路
类似于
⚱️
543. 二叉树的直径
,只不过本题目限制了路径的值需要相同
定义递归函数如下:univaluePath(root, ans)
  • root节点必须被使用到
  • 更新ans的时候可以使用两个子树
  • 返回最长路径时只能使用一颗子树
case 1 返回 0
notion imagenotion image
case 2 返回 1 + univaluePath(root.left)
notion imagenotion image
case 3 ans = max(ans, 2 + up(root.left, root.right)) 返回 max(up(root.left), up(root.right)) + 1
notion imagenotion image
题解
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: self.ans = 0 if root is None: return self.ans self.univaluePath(node=root) return self.ans def univaluePath(self, node): if node is None: return 0 l = self.univaluePath(node.left) r = self.univaluePath(node.right) pl, pr = 0, 0 if node.left and node.left.val == node.val: pl = l + 1 if node.right and node.right.val == node.val: pr = r + 1 self.ans = max(self.ans, pl + pr) return max(pl, pr)
notion imagenotion image
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: self.res = 1 self.helper(root) return self.res - 1 if self.res >= 2 else 0 def helper(self, root): if root is None: # [长度,该长度的值] return [0, 0] l = self.helper(root.left) r = self.helper(root.right) temp_l, temp_r = 0, 0 if l[0] != 0 and l[1] == root.val: temp_l += l[0] if r[0] != 0 and r[1] == root.val: temp_r += r[0] self.res = max(self.res, temp_l + temp_r + 1) return [max(temp_r, temp_l)+1, root.val]