In several recent posts I’ve presented C# code for a binary search tree where each data value is a (long) integer. Here is some additional code that shows how to traverse a tree in breadth-first and depth-first traversals.
public void DisplayBF()
{
// breadth-first using a queue
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(this.root);
while (q.Count > 0)
{
TreeNode n = q.Dequeue();
Console.WriteLine(n.data);
if (n.left != null)
q.Enqueue(n.left);
if (n.right != null)
q.Enqueue(n.right);
}
}
public void DisplayDF()
{
// depth-first using a stack
Stack<TreeNode> s = new Stack<TreeNode>();
s.Push(this.root);
while (s.Count > 0)
{
TreeNode n = s.Pop();
Console.WriteLine(n.data);
if (n.left != null)
s.Push(n.left);
if (n.right != null)
s.Push(n.right);
}
}
The code for the two methods is identical except that breath-first traversal uses a queue and depth-first traversal uses a stack. Calling the methods could look like:
BinarySearchTree bst = new BinarySearchTree();
bst.Insert(50); // level 0
bst.Insert(30); // level 1
bst.Insert(10); // level 2
bst.Insert(20); // level 3
bst.Insert(80); // level 1
bst.Insert(60); // level 2
bst.Insert(70); // level 3
bst.DisplayBF();
bst.DisplayDF();
The output from DisplayBF would be: 50, 30, 80, 10, 60, 20, 70. Each level of the tree is displayed from top to bottom.
The output from DisplayDF would be: 50, 80, 60, 70, 30, 10, 20. Each branch is displayed as far as possible before backing up and going again.

.NET Test Automation Recipes
Software Testing
SciPy Programming Succinctly
Keras Succinctly
R Programming
2026 Visual Studio Live
2025 Summer MLADS Conference
2026 DevIntersection Conference
2025 Machine Learning Week
2025 Ai4 Conference
2026 G2E Conference
2026 iSC West Conference
You must be logged in to post a comment.