分别计算左右孩子的二进制树

Count binary tree left and right children separately

本文关键字:二进制 孩子 左右 计算      更新时间:2023-10-16

我的代码仅计算二进制树的正确子女的数量。

int count(Arbin<T> a){
if(a.isEmpty()) return 0;
int num_l=0, num_r=0;
if(!a.leftChild.isEmpty()) 
    num_l = count(a.leftChild());
if(!a.rightChild.isEmpty()) 
    num_r = count(a.rightChild())+1;
return num_l+num_r;}

如何修改它,以便我可以分别获得合适的孩子的数量和左派孩子的数量?

Arbin类仅允许我进行此操作(而且我无法修改):

  • rightChild():返回正确的孩子的节点
  • leftChild():返回左儿童的节点
  • isEmpty():返回节点是否为空

如果您可以修改count(),请执行以下操作:

void count(Arbin<T> a, int& l, int& r){
if(a.isEmpty()) return ;
if(!a.leftChild.isEmpty()) 
    count(a.leftChild(), l+1, r);
if(!a.rightChild.isEmpty()) 
    count(a.rightChild(), l, r+1);
}

现在将count称为以下

int l = 0, r = 0;
count(tree, l, r);
// here you've left child count in `l` and right count in `r`