对于LeetCode练习时,有时需要直观的将树打印,提供如下demo供参考
输入
9
1,2,3,4,5,6,7,8,9,
效果
直接上代码
#include "stdio.h"
#include "string.h"
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int *ArrIn(int *pArrSize);
struct TreeNode *TreeIn(int *arr, int arrSize, int curIndex);
void Display(struct TreeNode *root, int ident);
int main()
{
int arrSize;
int* arr = ArrIn(&arrSize);
struct TreeNode *root = TreeIn(arr, arrSize, 0);
Display(root, 0);
return 0;
}
int *ArrIn(int *pArrSize)
{
int arrSize;
scanf("%d", &arrSize);
printf("==================\n");
int *arr = (int *)malloc(sizeof(int) * arrSize);
for (int i = 0; i < arrSize; i++) {
scanf("%d,", &arr[i]);
}
for (int i = 0; i < arrSize; i++) {
printf("%3d", arr[i]);
}
printf("\n==================\n");
*pArrSize = arrSize;
return arr;
}
void PreOrderTree(struct TreeNode *root)
{
if (root == NULL) {
return;
}
printf("%d ", root->val);
PreOrderTree(root->left);
PreOrderTree(root->right);
return;
}
int vec_left[100] = {0};
// 显示二叉树的函数,只要调用Display(root, 0)即可
void Display(struct TreeNode* root, int ident)
{
if(ident > 0) {
for(int i = 0; i < ident - 1; ++i) {
if (vec_left[i]) {
printf("%s", "| ");
} else {
printf("%s", " ");
}
}
printf("%s", "|-- ");
}
if(! root) {
printf("(null)\n");
return;
}
printf("%d\n", root->val);
if(!root->left && !root->right) {
return;
}
vec_left[ident] = 1;
Display(root->left, ident + 1);
vec_left[ident] = 0;
Display(root->right, ident + 1);
}
struct TreeNode *TreeIn(int *arr, int arrSize, int curIndex)
{
if (curIndex >= arrSize || arr[curIndex] == -1) { // -1 表示空节点
return NULL;
}
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = arr[curIndex];
root->left = TreeIn(arr, arrSize, curIndex * 2 + 1);
root->right = TreeIn(arr, arrSize, curIndex * 2 + 2);
return root;
}