-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution865.cs
40 lines (35 loc) · 957 Bytes
/
Solution865.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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution865
{
/// <summary>
/// 865. Smallest Subtree with all the Deepest Nodes - Medium
/// <a href="https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes">See the problem</a>
/// </summary>
public TreeNode SubtreeWithAllDeepest(TreeNode root)
{
return Helper(root).node;
}
private (TreeNode node, int depth) Helper(TreeNode node)
{
if (node == null)
{
return (null, 0);
}
var left = Helper(node.left);
var right = Helper(node.right);
if (left.depth > right.depth)
{
return (left.node, left.depth + 1);
}
else if (left.depth < right.depth)
{
return (right.node, right.depth + 1);
}
else
{
return (node, left.depth + 1);
}
}
}