Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging binary trees

I've written a quite primitive binary tree and it works just fine. The problem is, debugging it is a pain, actually seeing what each node contains and all their children and grandchildren is very tedious. Are there any visualizers so I can just get a tree representation of the data when I'm debugging it?

like image 764
Overly Excessive Avatar asked Apr 02 '26 21:04

Overly Excessive


1 Answers

You can build "poor man's visualizer" by overriding ToString and producing a tree representation that humans can read, like this:

string ToString() {
    var leftSub = left != null ? left.ToString() : "-";
    var rightSub = right != null ? right.ToString() : "-";
    return string.Format("[{0}:{1},{2}]", data, leftSub, rightSub);
}

For example, for a binary tree that looks like this

      6
     / \
    /   9
   3
  /  \
 1    4

this code should produce this output:

[6:[3:[1:-,-],[4:-,-]],[9:-,-]]
like image 189
Sergey Kalinichenko Avatar answered Apr 04 '26 12:04

Sergey Kalinichenko