# 如何印出 2D Binary tree 要印出 Binary tree 只要用 preorder postorder 或是 inorder 尋訪每個 node 就能夠把裡面的資料都印出來了,但那樣印出來的資料是1維的,很難直觀的看出每個 node 之間的連結。本文主要探討要如何以2維的方式印出一個binary tree,先上結果圖。 ![](https://i.imgur.com/xCrK1Q4.png) 先把 code 放上來 ```c= void print_tab(int i) { for (int j = 0; j < i; j++) printf("|\t"); } void print_tree(node_t *root, int i) { if (root == NULL) return; print_tree(root->right, i + 1); if (i != 0) { print_tab(i - 1); printf("|=======%d\n", root->key); } else printf("%d\n", root->key); print_tree(root->left, i + 1); } ``` 使用時呼叫 ```c print_tree(root, 0); ``` 基本上的核心概念就是,依照 `node` 的深度印出對印數量的 `|` 和空格,這裡空格我是用 `\t` 作為空格,可以換成固定長度的空格鍵,假設一個 `node` 深度為 `d` ,則印出 `(d-1)` 個 `|\t` 越深的node前面要印出越多個 |\t ,用 recursive的方式每次遞迴就把深度d +1