forked from algorithm001/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_687_2.cs
More file actions
58 lines (51 loc) · 1.14 KB
/
LeetCode_687_2.cs
File metadata and controls
58 lines (51 loc) · 1.14 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace leetcode
{
public class 最长同值路径
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
int max = 0;
public int LongestUnivaluePath(TreeNode root)
{
F(root);
return max;
}
int F(TreeNode root)
{
if (root == null)
{
return 0;
}
int left = F(root.left);
int right = F(root.right);
if (root.val == root?.left?.val)
{
left++;
}
else
{
left = 0;
}
if (root.val == root?.right?.val)
{
right++;
}
else
{
right = 0;
}
max = Math.Max(left + right, max);
return Math.Max(left, right);
}
}
}