Last active
February 25, 2016 19:47
-
-
Save DeepSky8/147bcd0955ebe368685f to your computer and use it in GitHub Desktop.
BreadthTraverse gets stuck somewhere. When I use the debug feature, Visual Studio hits an error and closes after line 173.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace BinaryTree | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var newBST = new BSTNode<int>(); | |
newBST.Add(12); | |
newBST.Add(6); | |
newBST.Add(18); | |
newBST.Add(3); | |
newBST.Add(14); | |
newBST.Add(9); | |
newBST.Add(17); | |
newBST.PrintString(); | |
} | |
} | |
public class BSTNode<T> where T : IComparable<T> | |
{ | |
public T Value { get; set; } | |
public BSTNode<T> Right { get; protected set; } | |
public BSTNode<T> Left { get; protected set; } | |
public bool Printed { get; protected set; } | |
public int Count { get; protected set; } = 0; | |
public void Add(T newValue) | |
{ | |
var newNode = new BSTNode<T>(); | |
//If this node does not hold a value, set it to the value currently being added. If the node equals 0, increment the Count at this node. | |
if (Value == null || Value.Equals(0)) | |
{ | |
if (Value.Equals(newValue)) | |
{ | |
Count += 1; | |
} | |
Value = newValue; | |
} | |
//If there is a value in the node, or the base node value is not 0, compare the new value to the current node value. | |
//Either increment the count by 1, or determine if child node [left or right] exists. | |
//Call Add with the newValue on the (possibly newly created) [left or right] node. | |
else | |
{ | |
switch (Value.CompareTo(newValue)) | |
{ | |
case 0: | |
Count += 1; | |
break; | |
case -1: | |
if (Left == null) | |
{ | |
Left = newNode; | |
} | |
Left.Add(newValue); | |
break; | |
case 1: | |
if (Right == null) | |
{ | |
Right = newNode; | |
} | |
Right.Add(newValue); | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
public string PrintString() | |
{ | |
var toPrint = new StringBuilder(); | |
if (Left != null) | |
{ | |
Left.PrintString(); | |
} | |
else | |
{ | |
for (int i = Count; i > 0; i--) | |
{ | |
toPrint.Append(Value + ", "); | |
} | |
if (Right != null) | |
{ | |
Right.PrintString(); | |
} | |
else | |
{ | |
for (int i = Count; i > 0; i--) | |
{ | |
toPrint.Append(Value + ", "); | |
} | |
} | |
} | |
return toPrint.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment