Traverse Binary Tree: Depth First

Problem: Traverse a given binary tree, depth first.

Solution 1: Iterate via a Stack

public class Node<T>
{
  public T Val;
  public Node<T> Left;
  public Node<T> Right;
}

public void DepthTraversal(Node n)
{
  Stack s = new Stack<Node>();
  s.Push(n);

  while (s.Any())
  {
    var current = s.Pop();
    if (current.Right != null) s.Push(current.Right);
    if (current.Left != null) s.Push(current.Left);

    Console.WriteLine(current.Val);
  }
}

Leave a comment

Design a site like this with WordPress.com
Get started