-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiameterOfBinaryTree.cs
More file actions
113 lines (86 loc) · 3.02 KB
/
Copy pathDiameterOfBinaryTree.cs
File metadata and controls
113 lines (86 loc) · 3.02 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using LeetCode.Solutions.Models;
namespace Solutions.Problems;
public class DiameterOfBinaryTreeSolution
{
public int DiameterOfBinaryTreeBruteForce(TreeNode? root)
{
static int Depth(TreeNode? node)
{
if (node == null)
return 0;
return 1 + Math.Max(Depth(node.left), Depth(node.right));
}
if (root == null)
return 0;
int leftHeight = Depth(root.left);
int rightHeight = Depth(root.right);
int diameter = leftHeight + rightHeight;
int sub = Math.Max(DiameterOfBinaryTreeBruteForce(root.left), DiameterOfBinaryTreeBruteForce(root.right));
return Math.Max(diameter, sub);
}
#region ClassMemberDFS
public int result = 0;
public int DiameterOfBinaryTreeClassMemberDFS(TreeNode? root)
{
int Depth(TreeNode? node)
{
if (node == null)
return 0;
var left = Depth(node.left);
var right = Depth(node.right);
result = Math.Max(result, left + right);
return Math.Max(left, right) + 1;
}
Depth(root);
return result;
}
#endregion
public int DiameterOfBinaryTreeDFS(TreeNode? root)
{
static int Depth(TreeNode? node, ref int result)
{
if (node == null)
return 0;
var left = Depth(node.left, ref result);
var right = Depth(node.right, ref result);
result = Math.Max(result, left + right);
return Math.Max(left, right) + 1;
}
int result = 0;
Depth(root, ref result);
return result;
}
public int DiameterOfBinaryTreeIterativeDFS(TreeNode? root)
{
if (root == null)
return 0;
var hashMap = new Dictionary<TreeNode, (int height, int diameter)>();
Stack<TreeNode> stack = new();
stack.Push(root);
while (stack.Count > 0)
{
TreeNode node = stack.Peek();
if (node.left != null && !hashMap.ContainsKey(node.left))
{
stack.Push(node.left);
continue;
}
if (node.right != null && !hashMap.ContainsKey(node.right))
{
stack.Push(node.right);
continue;
}
node = stack.Pop();
(int leftHeight, int leftDiameter) = (0, 0);
if (node.left != null && hashMap.TryGetValue(node.left, out var valueLeft))
(leftHeight, leftDiameter) = valueLeft;
(int rightHeight, int rightDiameter) = (0, 0);
if (node.right != null && hashMap.TryGetValue(node.right, out var valueRight))
(rightHeight, rightDiameter) = valueRight;
int diameter = Math.Max(leftHeight + rightHeight, Math.Max(leftDiameter, rightDiameter));
int height = 1 + Math.Max(leftHeight, rightHeight);
hashMap[node] = (height, diameter);
}
return hashMap[root].diameter;
}
}