用递归的方案实现:
/* 求二叉树的深度 */
int getDepthBiTree(BITREENODE* T)
{
int lDepth = 0, rDepth = 0;
if(T == NULL)
{
return 0;
}
else
{
lDepth = getDepthBiTree(T->lchild);
rDepth = getDepthBiTree(T->rchild);
}
return lDepth > rDepth ? lDepth+1 : rDepth+1;
}
完整的代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
/* 二叉树存储结构定义*/
typedef char TypeData;
typedef struct BiTreeNode
{
TypeData data;
struct BiTreeNode *lchild, *rchild;
}BITREENODE;
BITREENODE* createBiTree(); /* 创建二叉树 */
void preOrderBiTree(BITREENODE* T); /* 前序遍历该二叉树 */