当前位置:   article > 正文

用递归方法求二叉树(二叉链表结构)双分支节点的个数_递归计算树的双分支结点

递归计算树的双分支结点

求解的方法

  1. int DsonNodes(BiTree T){
  2. if(T == NULL) return 0;
  3. if(T->lchild && T->rchild){
  4. return DsonNodes(T->lchild) + DsonNodes(T->rchild) + 1;
  5. }
  6. return DsonNodes(T->lchild) + DsonNodes(T->rchild);
  7. }

此方法运行的环境

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #define maxsize 100
  5. //二叉树的创建序列
  6. //ab#df###c#e##
  7. //abd##e##cf###
  8. typedef struct BiNode{
  9. char date;
  10. struct BiNode *lchild,*rchild;
  11. }BiNode,*BiTree;
  12. BiNode* CreateBiTree();
  13. void Traverse(BiNode *p);
  14. int DsonNodes(BiTree T);
  15. int main(){
  16. BiTree t = CreateBiTree();
  17. printf("双分支节点的个数:%d",DsonNodes(t));
  18. return 0;
  19. }
  20. //用递归方法以中序遍历的方式创建二叉树
  21. BiNode* CreateBiTree(){
  22. BiNode *p;
  23. char a;
  24. scanf("%c",&a);
  25. if(a=='#')
  26. p=NULL;
  27. else{
  28. p=(BiNode *)malloc(sizeof(BiNode));
  29. p->date=a;
  30. p->lchild=CreateBiTree();
  31. p->rchild=CreateBiTree();
  32. }
  33. return p;
  34. }
  35. //递归方法中序遍历二叉树
  36. void Traverse(BiNode *p){
  37. if(p==NULL){
  38. return;
  39. }
  40. else{
  41. Traverse(p->lchild);
  42. printf("%c",p->date);
  43. Traverse(p->rchild);
  44. }
  45. return;
  46. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/737619
推荐阅读
相关标签
  

闽ICP备14008679号