求二叉树的深度代码实现

用递归的方案实现:

 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

 

转载于:https://www.cnblogs.com/guxuanqing/p/5884688.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值