[LeetCode] 687. Longest Univalue Path_Medium tag: DFS recursive
2018-07-18 06:25 Johnson_强生仔仔 阅读(211) 评论(0) 编辑 收藏 举报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
class Solution: def maxUnivaluePath(self, root): ans = [None] def maxPathWithRoot(root): if not root: return 0 left, right = maxPathWithRoot(root.left), maxPathWithRoot(root.right) left = 1 + left if root.left and root.val == root.left.val else 0 right = 1 + right if root.right and root.val == root.right.val else 0 local = max(0, left, right) potential = max(local, left + right) if ans[0] is None or potential > ans[0]: ans[0] = potential return local if not root: return 0 maxPathWithRoot(root) return ans[0]