减少泛型树遍历中的分支 所以我不完全确定这个问题是属于这里还是软件工程,但是因为我特别感兴趣C++的实现,我在这里问。

减少泛型树遍历中的分支 所以我不完全确定这个问题是属于这里还是软件工程,但是因为我特别感兴趣C++的实现,我在这里问。,c++,algorithm,optimization,C++,Algorithm,Optimization,现在,我已经实现了一个基本的二叉树,它带有一个通用的遍历函数,可以同时处理预序、顺序和后序 void BiTree::_trav(BiNode* root, int offset, function<void (int&,int&)> lambda) { if (root == NULL) {return;} auto call = [&] () {lambda(root->data, root->sc);}; if (

现在,我已经实现了一个基本的二叉树,它带有一个通用的遍历函数,可以同时处理预序、顺序和后序

void BiTree::_trav(BiNode* root, int offset, function<void (int&,int&)> lambda) {

    if (root == NULL) {return;}
    auto call = [&] () {lambda(root->data, root->sc);};

    if (offset == 0) { call();}

    _trav(root->child[0], offset, lambda);

    if (offset == 1) { call();}

    _trav(root->child[1], offset, lambda);

    if (offset == 2) { call();}
}

我的编程直觉告诉我,有一种更好的方法可以做到这一点,分支更少,但我不知道怎么做。switch语句不起作用,因为
do-thing()
被多次调用,或者有更多的分支。因此,我感兴趣的是如何用最小的分支进行泛型树遍历。

因此,我使用一组伪函数来回答我自己的问题,并用我真正想要运行的代码插入函数。我不确定这是否会提高性能,但它似乎减少了分支

void BiTree::_trav(BiNode* root, int offset, function<void (int&,int&)> lambda) {
    if (root == NULL) {return;}

    function<void (void)> branches[3];
    for(int i = 0; i < 3; i++) {
        branches[i] = [&] () {};
    }
    function<void (void)> call  = [&] () {lambda(root->data, root->sc);};
    branches[offset] = call;

    branches[0]();

    _trav(root->child[0], offset, lambda);

    branches[1]();

    _trav(root->child[1], offset, lambda);

    branches[2]();
}
void位树::_trav(BiNode*root,int offset,函数lambda){
如果(root==NULL){return;}
职能部门[3];
对于(int i=0;i<3;i++){
分支[i]=[&](){};
}
函数调用=[&](){lambda(root->data,root->sc);};
分支[偏移]=呼叫;
分支[0]();
_trav(根->子项[0],偏移量,λ);
分支机构[1]();
_trav(根->子项[1],偏移量,λ);
分支机构[2]();
}

一体机和最高性能往往是相互矛盾的目标。假设每个函数只有5行代码,那么通过编写三个单独的函数来实现最大性能:预排序、顺序和后排序。它不仅消除了分支,而且还消除了在每次调用时传递
offset
的需要。
void BiTree::_trav(BiNode* root, int offset, function<void (int&,int&)> lambda) {
    if (root == NULL) {return;}

    function<void (void)> branches[3];
    for(int i = 0; i < 3; i++) {
        branches[i] = [&] () {};
    }
    function<void (void)> call  = [&] () {lambda(root->data, root->sc);};
    branches[offset] = call;

    branches[0]();

    _trav(root->child[0], offset, lambda);

    branches[1]();

    _trav(root->child[1], offset, lambda);

    branches[2]();
}