求二叉树所有双分支结点个数

我用了2种方法,1.递归,2.非递归(层次遍历)

#include<iostream>
using namespace std;
typedef struct BiNode {
    char data;
    struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
typedef struct stack {
    BiTree data[1024];
    int top;
}stack;
typedef struct queue {
    BiTree data[1024];
    int front;
    int rear;
}queue;
void create(BiTree& t) {//二叉树先序
    char ch;
    cin >> ch;
    if (ch == '@')t = NULL;
    else {
        t = new BiNode;
        t->data = ch;
        create(t->lchild);
        create(t->rchild);
    }
}
void preorder(BiTree t) {
    BiTree s[1024];
    int top = 0;
    BiTree p = t;
   
    while (p || top != 0) {
        if (p) {
            s[top++] = p;
            cout << p->data;
            p = p->lchild;
        }
        else {
            p = s[--top];
            p = p->rchild;
        }
    }
}
void inorder(BiTree t) {
    BiTree s[1024];
    int top = 0;
    BiTree p = t;
    while (p || top != 0) {
        if (p) {
            s[top++] = p;
            p = p->lchild;
        }
        else {
            p = s[--top];
            cout << p->data;
            p = p->rchild;
        }
    }
}
int Btdepth(BiTree T) {
      BiTree q[1024];
    int front = 0, rear = 0;
    BiTree p = T;
    q[rear++] = p;
    int level = 0;
    int last = rear;
    while (front < rear) {
        p = q[front++];
        if (p->lchild)q[rear++] = p->lchild;
        if (p->rchild)q[rear++] = p->rchild;
        if (front == last) {
            level++;
            last = rear;
        }
    }
    return level;
}
int douNode(BiTree t) {
    if (!t)return true;//空树为满二叉树
    BiTree q[1024];
    int num = 0;
    int front = 0, rear = 0;
    BiTree p = t;
    q[rear++] = p;
    while (front != rear) {
        p = q[front++];
        if (p->lchild && p->rchild)num++;
        if (p->lchild)q[rear++] = p->lchild;
        if (p->rchild)q[rear++] = p->rchild;
    }
    return num;
}

int DsonNodes(BiTree t) {//递归
    if (t == NULL)return 0;
    if (t->lchild && t->rchild)return DsonNodes(t->lchild) + DsonNodes(t->rchild) + 1;
    else return DsonNodes(t->lchild) + DsonNodes(t->rchild);
}
int main() {
    BiTree t;
     create(t);//测试数据:1.abd@@e@@c@@  2.ABD@F@@@CE@@@

    //abcde先序
    //edcba中序
  
    
   /* preorder(t);
    inorder(t);*/
     /*cout << douNode(t);*/
     cout << DsonNodes(t);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值