-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution894.cs
58 lines (50 loc) · 1.44 KB
/
Solution894.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
46
47
48
49
50
51
52
53
54
55
56
57
58
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution894
{
private Dictionary<int, List<TreeNode>> memo = [];
/// <summary>
/// 894. All Possible Full Binary Trees - Medium
/// <a href="https://leetcode.com/problems/all-possible-full-binary-trees">See the problem</a>
/// </summary>
public IList<TreeNode> AllPossibleFBT(int n)
{
if (n % 2 == 0)
{
return []; // Full binary trees must have an odd number of nodes
}
if (memo.ContainsKey(n))
{
return memo[n];
}
var result = new List<TreeNode>();
if (n == 1)
{
result.Add(new TreeNode(0));
}
else
{
for (int leftNodes = 1; leftNodes < n; leftNodes += 2)
{
int rightNodes = n - 1 - leftNodes;
foreach (var left in AllPossibleFBT(leftNodes))
{
foreach (var right in AllPossibleFBT(rightNodes))
{
result.Add(new TreeNode(0, CloneTree(left), CloneTree(right)));
}
}
}
}
memo[n] = result;
return result;
}
private TreeNode CloneTree(TreeNode root)
{
if (root == null)
{
return null;
}
return new TreeNode(root.val, CloneTree(root.left), CloneTree(root.right));
}
}