Skip to content

Commit b27f63d

Browse files
committed
Fix PrintAsTree operation
1 parent 787f5bc commit b27f63d

File tree

3 files changed

+17
-13
lines changed

3 files changed

+17
-13
lines changed

samples/BinaryTreeConsole/Program.cs

+2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ private static void Main()
99
{
1010
var binaryTree = new BinaryTree<int> { 8, 5, 12, 3, 7, 10, 15 };
1111

12+
binaryTree.PrintAsTree();
13+
1214
Console.Write("Pre-order : ");
1315
binaryTree.TraversalStrategy = new PreOrderTraversal<int>();
1416
binaryTree.PrintToConsole();

src/BinaryTree/BinaryTree.cs

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace BinaryTree
77
public class BinaryTree<T> : ICollection<T> where T : IComparable<T>
88
{
99
private ITraversalStrategy<T> _traversalStrategy;
10-
public BinaryTreeNode<T> _head;
10+
private BinaryTreeNode<T> _head;
1111

1212
public BinaryTree(ITraversalStrategy<T> traversalStrategy)
1313
{
@@ -34,6 +34,8 @@ public BinaryTree()
3434
{
3535
}
3636

37+
public BinaryTreeNode<T> Head => _head;
38+
3739
public ITraversalStrategy<T> TraversalStrategy
3840
{
3941
get => _traversalStrategy ?? (_traversalStrategy = new InOrderTraversal<T>());

src/BinaryTree/EnumerableExtensions.cs

+12-12
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,28 @@ public static class EnumerableExtensions
77
{
88
public static void PrintToConsole<T>(this IEnumerable<T> source)
99
{
10-
if (source is BinaryTree<int>)
10+
foreach (var item in source)
1111
{
12-
BinaryTree<int> binaryTree = (BinaryTree<int>)source;
13-
binaryTree.Print();
12+
Console.Write($"{item} ");
1413
}
15-
else
14+
}
15+
16+
public static void PrintAsTree<T>(this IEnumerable<T> source)
17+
{
18+
if (source is BinaryTree<int> binaryTree)
1619
{
17-
foreach (var item in source)
18-
{
19-
Console.Write($"{item} ");
20-
}
20+
binaryTree.Print();
21+
return;
2122
}
22-
23-
23+
throw new NotSupportedException("Support only for numbers");
2424
}
2525

26-
public static void Print(this BinaryTree<int> root, string textFormat = "0", int spacing = 1, int topMargin = 2, int leftMargin = 2)
26+
private static void Print(this BinaryTree<int> root, string textFormat = "0", int spacing = 1, int topMargin = 2, int leftMargin = 2)
2727
{
2828
if (root == null) return;
2929
int rootTop = Console.CursorTop + topMargin;
3030
var last = new List<NodeInfo>();
31-
var next = root._head;
31+
var next = root.Head;
3232
for (int level = 0; next != null; level++)
3333
{
3434
var item = new NodeInfo { Node = next, Text = next.Value.ToString(textFormat) };

0 commit comments

Comments
 (0)