【算法笔记】求双分支节点个数

int countDsonNodes(bitree b)
{ int a=0;
    if(b==NULL)
        return 0;
    if(b->lchild!=NULL&&b->rchild!=NULL)
        a++;

    a=a+countDsonNodes(b->lchild);

    a=a+countDsonNodes(b->rchild);
    return a;
}

完整代码

#include 

using namespace std;

struct TreeNode {
    int data;
    struct TreeNode* lchild;
    struct TreeNode* rchild;
};

typedef struct TreeNode* bitree;

bitree createNode(int data) {
    bitree newNode = new TreeNode;
    newNode->data = data;
    newNode->lchild = NULL;
    newNode->rchild = NULL;
    return newNode;
}

int countDsonNodes(bitree b)
{ int a=0;
    if(b==NULL)
        return 0;
    if(b->lchild!=NULL&&b->rchild!=NULL)
        a++;

    a=a+countDsonNodes(b->lchild);

    a=a+countDsonNodes(b->rchild);
    return a;
}

int main() {
    // 创建二叉树
    bitree root = createNode(1);
    root->lchild = createNode(2);
    root->rchild = createNode(3);
    root->lchild->lchild = createNode(4);
    root->lchild->rchild = createNode(5);
    root->rchild->lchild = createNode(6);
    root->rchild->rchild = createNode(7);

    // 统计度为2的节点个数
    int dsonCount = countDsonNodes(root);
    cout << "度为2的节点个数为:" << dsonCount << endl;

    return 0;
}

通过本题注意用递归时的返回值

错误代码:

int dsonnodes(bitree b)
{ int a=0;
    if(b==NULL)
        return 0;
    if(b.lchild!=NULL&&b.rchild!=NULL)
        a++;
   
    dsonnodes(b.lchild);
   
    dsonnodes(b.rchild);
    return a;
}

没有将左右结果返回

完整代码

#include 

// 二叉树节点结构体
struct TreeNode {
    int data;
    TreeNode* lchild;
    TreeNode* rchild;
    TreeNode(int val) : data(val), lchild(nullptr), rchild(nullptr) {}
};

// 判断二叉树节点是否有两个子节点
int countNodesWithTwoChildren(TreeNode* root) {
    if (root == nullptr) {
        return 0;
    }

    int count = 0;

    if (root->lchild != nullptr && root->rchild != nullptr) {
        count = 1;
    }

    // 递归遍历左子树和右子树
    int leftCount = countNodesWithTwoChildren(root->lchild);
    int rightCount = countNodesWithTwoChildren(root->rchild);

    // 返回当前子树和左右子树中满足条件的节点数量之和
    return count + leftCount + rightCount;
}

int main() {
    // 创建示例二叉树
    TreeNode* root = new TreeNode(1);
    root->lchild = new TreeNode(2);
    root->rchild = new TreeNode(3);
    root->lchild->lchild = new TreeNode(4);
    root->lchild->rchild = new TreeNode(5);
    root->rchild->lchild = new TreeNode(6);
    root->rchild->rchild = new TreeNode(7);

    // 计算具有两个子节点的节点数量
    int result = countNodesWithTwoChildren(root);

    std::cout << "Number of nodes with two children: " << result << std::endl;

    // 释放动态分配的内存,防止内存泄漏
    delete root->rchild->rchild;
    delete root->rchild->lchild;
    delete root->rchild;
    delete root->lchild->rchild;
    delete root->lchild->lchild;
    delete root->lchild;
    delete root;

    return 0;
}

你可能感兴趣的:(算法,数据结构)