687. Longest Univalue Path

687. Longest Univalue Path

题目描述

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.

1
2
3
4
5
6
7
8
9
10
11
12
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
1
2
3
4
5
6
7
8
9
10
11
12
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.

题目大意

求二叉树节点值全部相等的最长路径,路径不一定通过根节点。

解题思路

递归遍历左右子树,寻找左右子树节点值全部相等的最长路径。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func longestUnivaluePath(_ root: TreeNode?) -> Int {
var ans = 0
func longestPath(_ root: TreeNode?) -> Int {
guard let tree = root else { return 0 }
let lc = longestPath(tree.left)
let rc = longestPath(tree.right)
var ll = 0, rl = 0
if let left = tree.left, left.val == tree.val { ll = lc + 1 }
if let right = tree.right, right.val == tree.val { rl = rc + 1 }
ans = max(rl + ll, ans)
return max(rl, ll)
}
longestPath(root)
return ans
}
}
0%