-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvertBinaryTree.cs
More file actions
77 lines (60 loc) · 1.75 KB
/
InvertBinaryTree.cs
File metadata and controls
77 lines (60 loc) · 1.75 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
using LeetCode.Solutions.Models;
namespace Solutions.Problems;
public class InvertBinaryTreeSolution
{
/// <summary>
/// DFS Recursive Solution
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public TreeNode? InvertTreeRecursiveDFS(TreeNode? root)
{
if (root == null)
return null;
(root.left, root.right) = (root.right, root.left);
InvertTreeRecursiveDFS(root.right);
InvertTreeRecursiveDFS(root.left);
return root;
}
/// <summary>
/// Iterative DFS Solution
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public TreeNode? InvertTree(TreeNode? root)
{
if (root == null)
return null;
Stack<TreeNode> stack = new();
stack.Push(root);
while (stack.Count > 0)
{
TreeNode node = stack.Pop();
(node.left, node.right) = (node.right, node.left);
if (node.left != null) stack.Push(node.left);
if (node.right != null) stack.Push(node.right);
}
return root;
}
/// <summary>
/// BFS Algo
/// Algoritmo de Busca em Largura
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public TreeNode? InvertTreeBFS(TreeNode root)
{
if (root == null)
return null;
Queue<TreeNode> queue = new();
queue.Enqueue(root);
while (queue.Count > 0)
{
TreeNode node = queue.Dequeue();
(node.left, node.right) = (node.right, node.left);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
return root;
}
}