这个程序在二叉树层次遍历的递归实现中曾用到过,程序如下:
- #include<iostream>
- #include<stack>
- #define N 7
- using namespace std;
- typedef struct node
- {
- struct node *leftChild;
- struct node *rightChild;
- int data;
- }BiTreeNode, *BiTree;
- // 生成一个结点
- BiTreeNode *createNode(int i)
- {
- BiTreeNode * q = new BiTreeNode;
- q->leftChild = NULL;
- q->rightChild = NULL;
- q->data = i;
- return q;
- }
- BiTree createBiTree()
- {
- BiTreeNode *p[N];
- int i;
- for(i = 0; i < N; i++)
- p[i] = createNode(i + 1);
- // 把结点连接成树
- for(i = 0; i < N/2; i++)
- {
- p[i]->leftChild = p[i * 2 + 1];
- p[i]->rightChild = p[i * 2 + 2];
- }
- return p[0];
- }
- int max(int x, int y)
- {
- return x > y ? x : y;
- }
- int getDepth(BiTree T)
- {
- if(NULL == T)
- return 0;
- return 1 + max(getDepth(T->leftChild), getDepth(T->rightChild));
- }
- int main()
- {
- BiTree T = createBiTree();
- cout << getDepth(T) << endl;
- return 0;
- }