[LeetCode] 687. Longest Univalue Path_Easy tag: DFS recursive

本文介绍了一个二叉树问题,即寻找具有相同节点值的最长路径,并给出了使用深度优先搜索解决该问题的方法。路径长度由连接的节点数表示,路径不必通过根节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

Note: The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5

 

Output:

2

 

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5

 

Output:

2

 

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

 

这个题目的思路实际上跟 [LeetCode] 124. Binary Tree Maximum Path Sum 很像, 就是用一个helper function(input: root, output: 包括root的最长的univalue path 的number of nodes),

然后注意self.ans 是跟 1+ l + r 比较, 但是返回的时候只返回 1+ max(l, r), 最后返回self.ans -1 (因为题目求的是边)

 

1. Constraints

1) empty => 0

2) 1 node => 0

3) element will be interger

 

2. Ideas

DFS      T: O(n)     S; O(n)

1) self.ans = 1 # 这样方便判断如果not root 的情况

2) helper function, check l, r , if not 0, check root.val == root.child.val, update self.ans = max(self.ans, 1+ l+ r)

3) return self.ans -1

 

3. Code

 1 class Solution:
 2     def maxUnivaluePath(self, root):
 3         self.ans = 1
 4         def helper(root):
 5             if not root: return 0
 6             l, r = helper(root.left), helper(root.right)
 7             l = l if l != 0 and root.val == root.left.val else 0
 8             r = r if r != 0 and root.val == root.right.val else 0
 9             self.ans = max(self.ans, 1 + l + r )
10             return max(l, r) + 1
11         helper(root)
12         return self.root -1

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9327061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值