-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution993.cs
45 lines (38 loc) · 1.02 KB
/
Solution993.cs
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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution993
{
/// <summary>
/// 993. Cousins in Binary Tree - Easy
/// <a href="https://leetcode.com/problems/cousins-in-binary-tree">See the problem</a>
/// </summary>
public bool IsCousins(TreeNode root, int x, int y)
{
var xParent = 0;
var yParent = 0;
var xDepth = 0;
var yDepth = 0;
void Dfs(TreeNode node, int parent, int depth)
{
if (node == null)
{
return;
}
if (node.val == x)
{
xParent = parent;
xDepth = depth;
}
else if (node.val == y)
{
yParent = parent;
yDepth = depth;
}
Dfs(node.left, node.val, depth + 1);
Dfs(node.right, node.val, depth + 1);
}
Dfs(root, 0, 0);
return xParent != yParent && xDepth == yDepth;
}
}