分别计算二元树左右儿童

时间:2017-09-10 20:04:40

标签: c++ data-structures binary-tree

我有这个代码只计算二叉树的正确子项数。

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():返回节点是否为空

1 个答案:

答案 0 :(得分:1)

如果您可以修改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`