求二叉树的深度代码实现

用递归的方案实现:

复制代码
 1 /* 求二叉树的深度 */
 2 int getDepthBiTree(BITREENODE* T)
 3 {
 4     int lDepth = 0, rDepth = 0;
 5 
 6     if(T == NULL)
 7     {
 8         return 0;
 9     }
10     else
11     {
12         lDepth = getDepthBiTree(T->lchild);
13         rDepth = getDepthBiTree(T->rchild);
14     }
15 
16     return lDepth > rDepth ? lDepth+1 : rDepth+1;
17 }
复制代码

完整代码

复制代码
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 
 6 using namespace std;
 7 
 8 /* 二叉树存储结构定义*/
 9 typedef char TypeData;
10 typedef struct BiTreeNode
11 {
12     TypeData data;
13     struct BiTreeNode *lchild, *rchild;
14 }BITREENODE;
15 
16 
17 BITREENODE* createBiTree();          /* 创建二叉树 */
18 void preOrderBiTree(BITREENODE* T);  /* 前序遍历该二叉树 */
19 
20 
21 /* 创建二叉树 */
22 BITREENODE* createBiTree()
23 {
24     TypeData ch = 0;
25     BITREENODE* pNewNode = NULL;
26 
27     cin >> ch;
28 
29     if(ch == '#')
30     {
31         pNewNode = NULL;
32     }
33     else
34     {
35         /* 给节点分配内存 */
36         pNewNode = (BITREENODE*)malloc(sizeof(BITREENODE));
37         pNewNode->data = ch;
38 
39         /* 递归构建左右子树 */
40         pNewNode->lchild = createBiTree();
41         pNewNode->rchild = createBiTree();
42     }
43 
44     return pNewNode;
45 }
46 
47 /* 前序遍历该二叉树 */
48 void preOrderBiTree(BITREENODE* T)
49 {
50     if(T)
51     {
52        cout << T->data << " ";
53        preOrderBiTree(T->lchild);
54        preOrderBiTree(T->rchild);
55     }
56 }
57 
58 /* 求二叉树的深度 */
59 int getDepthBiTree(BITREENODE* T)
60 {
61     int lDepth = 0, rDepth = 0;
62 
63     if(T == NULL)
64     {
65         return 0;
66     }
67     else
68     {
69         lDepth = getDepthBiTree(T->lchild);
70         rDepth = getDepthBiTree(T->rchild);
71     }
72 
73     return lDepth > rDepth ? lDepth+1 : rDepth+1;
74 }
75 
76 int main(void)
77 {
78     BITREENODE* pRoot = NULL;
79     int depth = 0;
80 
81     /* 创建二叉树 */
82     pRoot = createBiTree();
83 
84     /* 前序遍历该二叉树,这时候还没有线索化二叉树,可以这样进行前序遍历 */
85     preOrderBiTree(pRoot);
86     cout << endl;
87 
88     /* 求二叉树的深度*/
89     depth = getDepthBiTree(pRoot);
90     cout << depth << endl;
91 
92 
93     return 0;
94 }
View Code
复制代码

释放内存

复制代码
 1 void free_bitree(bitree *bt)
 2 {
 3     if (*bt) {
 4         if ((*bt)->lchild)
 5             free_bitree(&(*bt)->lchild);
 6         if ((*bt)->rchild)
 7             free_bitree(&(*bt)->rchild);
 8             free(*bt);
 9             *bt = NULL;
10     }
11 }
View Code
复制代码

 

posted @   PKICA  阅读(2661)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2015-09-19 int *p()与int (*p)()的区别
2015-09-19 int*p[ ]与int(*p)[ ]的区别
点击右上角即可分享
微信分享提示