C语言实现二叉树深度计算 - 完整代码解析
#include <stdio.h> #include <stdlib.h>
typedef int Status; typedef int TElemType;
#define OK 1 #define OVERFLOW -2
typedef struct BiTNode { TElemType data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree, *SElemType;
typedef struct SNode { SElemType data; struct SNode *next; }SNode;
Status CreateBiTree(BiTree *T) { char ch; scanf('%c', &ch);
if (ch == '#') {
*T = NULL;
} else {
*T = (BiTNode *)malloc(sizeof(BiTNode));
if (!*T) exit(OVERFLOW);
(*T)->data = ch;
CreateBiTree(&((*T)->lchild)); // Create left subtree
CreateBiTree(&((*T)->rchild)); // Create right subtree
}
return OK;
}
int DeepTree(BiTree T) { if (T == NULL) return 0;
int ldeep = DeepTree(T->lchild); // Calculate the depth of the left subtree
int rdeep = DeepTree(T->rchild); // Calculate the depth of the right subtree
int deep = ldeep > rdeep ? ldeep : rdeep;
return (deep + 1);
}
int main() { BiTree T; printf("Please enter the binary tree: "); CreateBiTree(&T); printf("The depth of the binary tree is: %d\n", DeepTree(T)); return 0; }
原文地址: https://www.cveoy.top/t/topic/cqR0 著作权归作者所有。请勿转载和采集!