#include<stdio.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node *left;
    struct Node *right;
};

int countSingleBranchNodes(struct Node *root){
    if(root == NULL){
        return 0;
    }
    if(root->left == NULL && root->right != NULL){
        return 1 + countSingleBranchNodes(root->right);
    }
    if(root->left != NULL && root->right == NULL){
        return 1 + countSingleBranchNodes(root->left);
    }
    return countSingleBranchNodes(root->left) + countSingleBranchNodes(root->right);
}

struct Node * createNode(int value){
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main(){
    struct Node *root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);
    printf('Number of single branch nodes: %d\n', countSingleBranchNodes(root));
    return 0;
}
C语言递归算法计算二叉树单分支节点数量

原文地址: https://www.cveoy.top/t/topic/oAqa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录