Here is the code:
class Program
{
static void Main(string[] args)
{
BSTnode n = new BSTnode(5);
n.add(2);
n.add(7);
n.add(3);
n.add(1);
n.add(6);
n.add(8);
displayBST(n);
}
public static void displayBST(BSTnode n)
{
Stack<List<BSTnode>> d = new Stack<List<BSTnode>>();
d.Push(new List<BSTnode>() { n });
Console.WriteLine(n.data);
List<BSTnode> liTemp = null;
for (int i = 0; i < d.Count; i++)
{
liTemp = new List<BSTnode>();
foreach (var node in d.Peek())
{
if (node.LeftNode != null)
{
liTemp.Add(node.LeftNode);
Console.Write(node.LeftNode.data);
}
if (node.rightNode != null)
{
liTemp.Add(node.rightNode);
Console.Write(node.rightNode.data);
}
}
Console.WriteLine();
if (liTemp.Count > 0)
{
d.Push(liTemp);
}
}
}
}
public class BSTnode
{
public int data { get; set; }
public BSTnode LeftNode { get; set; }
public BSTnode rightNode { get; set; }
public BSTnode(int _data)
{
data = _data;
}
public void add(int _data)
{
BSTnode newN = new BSTnode(_data);
if (_data < data)
{
if (LeftNode != null)
{
LeftNode.add(_data);
}
else
{
LeftNode = newN;
}
}
else
{
if (rightNode != null)
{
rightNode.add(_data);
}
else
{
rightNode = newN;
}
}
}
}
Output:
5
27
1368
Press any key to continue . . .
This Solution is written by me and is not completely tested. Please comment if you found any alternative solutions or any enhancement to my solution.
Popular Posts
-
Here is the code: // => Brute Force Solution: O(m* n) static long arrayManipulation(int n, int[][] queries) { ...
-
Whatever it is one fine day everyone on this planet who are born have to die for sure. When you are close ones are with you, you wont know ...
-
HTML: <div class="outer-container"> <div class="inner-container"> <div class="t...
No comments:
Post a Comment