求二叉树的高度

来源:互联网 发布:扬子石化热电厂优化 编辑:程序博客网 时间:2024/04/28 03:41

      这个程序在二叉树层次遍历的递归实现中曾用到过,程序如下:

#include<iostream>#include<stack>#define N 7using 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;}