求二叉树的高度

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

[cpp]  view plain copy
  1. #include<iostream>  
  2. #include<stack>  
  3. #define N 7  
  4. using namespace std;  
  5.   
  6. typedef struct node  
  7. {  
  8.     struct node *leftChild;  
  9.     struct node *rightChild;  
  10.     int data;  
  11. }BiTreeNode, *BiTree;  
  12.   
  13. // 生成一个结点  
  14. BiTreeNode *createNode(int i)  
  15. {  
  16.     BiTreeNode * q = new BiTreeNode;  
  17.     q->leftChild = NULL;  
  18.     q->rightChild = NULL;  
  19.     q->data = i;  
  20.   
  21.     return q;  
  22. }  
  23.   
  24. BiTree createBiTree()  
  25. {  
  26.     BiTreeNode *p[N];  
  27.     int i;  
  28.     for(i = 0; i < N; i++)  
  29.         p[i] = createNode(i + 1);  
  30.   
  31.     // 把结点连接成树  
  32.     for(i = 0; i < N/2; i++)  
  33.     {  
  34.         p[i]->leftChild = p[i * 2 + 1];  
  35.         p[i]->rightChild = p[i * 2 + 2];  
  36.     }  
  37.   
  38.     return p[0];  
  39. }  
  40.   
  41. int max(int x, int y)  
  42. {  
  43.     return x > y ? x : y;  
  44. }  
  45.   
  46. int getDepth(BiTree T)  
  47. {  
  48.     if(NULL == T)  
  49.         return 0;  
  50.     return 1 + max(getDepth(T->leftChild), getDepth(T->rightChild));  
  51. }  
  52.   
  53. int main()  
  54. {  
  55.     BiTree T = createBiTree();  
  56.     cout << getDepth(T) << endl;  
  57.       
  58.     return 0;  
  59. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值