计算二叉树深度
#define _CRT_SECURE_NO_WARNINGS#include <iostream>
using namespace std;typedef char ElemType;
#define ERROR 0
#define OK 1
#define Maxsize 100
#define STR_SIZE 1024typedef struct BiTNode
{ElemType data;BiTNode* lchild, * rchild;
}BiTNode, * BiTree;void draw(BiTNode* root);bool Create_tree(BiTree& T) //递归创建二叉树
{ElemType x = 0;cin >> x;if (x == '#'){T = NULL;}else{T = (BiTree)malloc(sizeof(BiTNode));if (T == NULL){cout << "内存无法分配!!!" << endl;return ERROR;}T->data = x;T->lchild = NULL;T->rchild = NULL;Create_tree(T->lchild);Create_tree(T->rchild);}return OK;
}void PreOrder(BiTree T) //前序遍历非递归
{if (T != NULL){cout << T->data;PreOrder(T->lchild);PreOrder(T->rchild);}
}void InOrder(BiTree T) //中序遍历非递归
{if (T != NULL){InOrder(T->lchild);cout << T->data;InOrder(T->rchild);}
}void PostOrder(BiTree T) //后序遍历非递归
{if (T != NULL){PostOrder(T->lchild);PostOrder(T->rchild);cout << T->data;}
}//---------------------------------核心代码---------------------------------//
int depth(BiTree T) //递归操作
{int left, right;if (T == NULL){return 0;}else{left = depth(T->lchild);right = depth(T->rchild);return left > right ? left + 1 : right + 1;}
}
//---------------------------------核心代码---------------------------------//
//计算二叉树深度
//测试不同情况以验证程序性能
//测试树1:ABD##E##CF##G##
//测试树2:AB###
//测试树3:ABC###D##
//测试树4:ABCD####D##
//做题思路:根据要求写出递归表达式,之后可以画出递归图验证下看看是否正确。
int main(void)
{cout << "//------生成一颗树---------//" << endl;BiTree T = NULL;Create_tree(T);PreOrder(T);cout << endl;InOrder(T);cout << endl;PostOrder(T);cout << endl;cout << "//------生成一颗树---------//" << endl;cout << "//------原始树图形---------//" << endl;draw(T);cout << "树的深度为: " << depth(T) << endl;;return 0;
}//参考博客:https://blog.csdn.net/weixin_42109012/article/details/92250160
/*****************************************************************************
* @date 2020/4/19
* @brief 水平画树
* @param node 二叉树节点
* @param left 判断左右
* @param str 可变字符串
*****************************************************************************/
void draw_level(BiTNode* node, bool left, char* str) {if (node->rchild) {draw_level(node->rchild, false, strcat(str, (left ? "| " : " ")));}printf("%s", str);printf("%c", (left ? '\\' : '/'));printf("-----");printf("%c\n", node->data);if (node->lchild) {draw_level(node->lchild, true, strcat(str, (left ? " " : "| ")));}// " " : "| " 长度为 6str[strlen(str) - 6] = '\0';
}/*****************************************************************************
* @date 2020/4/19
* @brief 根节点画树
* @param root 二叉树根节点
*****************************************************************************/
void draw(BiTNode* root) {char str[STR_SIZE];memset(str, '\0', STR_SIZE);/*** 1. 在 windows 下,下面是可执行的* 2. 在 Linux 下,执行会报 Segmentation fault* 需要使用中间变量*/if (root->rchild) {draw_level(root->rchild, false, str);}printf("%c\n", root->data);if (root->lchild) {draw_level(root->lchild, true, str);}
}