在写二叉树时经常希望把它可视化,本文实现了相对直观地打印二叉树。
主要思路:
- 空节点使用 n (null)表示
- 通过节点的层数计算间隔
效果图如下:
代码实现:
using System;
using System.Collections.Generic;
namespace PrintBT {
public class BinaryTree {
public class Node {
public int data;
public Node left;
public Node right;
}
static bool IsAllElementsNull(Queue<Node> queue) {
foreach (Node node in queue) {
if (null != node)
return false;
}
return true;
}
public static int GetDepth(Node root) {
if (root == null)
return 0;
int depth1 = GetDepth(root.right);
int depth2 = GetDepth(root.left);
if (depth1 > depth2)
return depth1 + 1;
else
return depth2 + 1;
}
public static void PrintSpaces(int num) {
for (int i = 0; i < num; ++i)
Console.Write(" ");
}
public static void