使用 DFS 通过 AST 递归

Recursing through a AST using DFS

我正在尝试通过带注释的语法树进行递归。

我的目标是在看到特定类型的节点后增加计数器。

Void *DFS(State *N, IrNode *node, int Counter)
{    
    Counter=0

    if (node->irLeftChild == NULL && 
        node->irRightChild == NULL && 
        node->isVisited == false && 
        node->type == kNewtonIrNodeType_Tidentifier)
    {
        Counter+=1
        node->isVisited = true;
        return ;
    }

    DFS(N, node->irLeftChild);

    DFS(N, node->irRightChild); 
}

有没有更好的递归树的方法?

我不确定你想做什么;但是如果你想 return 符合调用者标准的条目总数,你可能需要这样的东西:

int DFS(State *N, IrNode *node) {    
    int Counter = 0;

    if (node->irLeftChild == NULL &&  node->irRightChild == NULL &&  node->isVisited == false && node->type == kNewtonIrNodeType_Tidentifier) {
        Counter += 1;
        node->isVisited = true;
    }
    Counter += DFS(N, node->irLeftChild);
    Counter += DFS(N, node->irRightChild); 
    return Counter;
}