首页 > 解决方案 > 二叉树中节点的级别

问题描述

为什么没有打印节点的级别?每次调用后级别都会增加?代码中的问题在哪里?

int levelNode(struct Node* root,int a,int level){
    if(root==NULL){
        return 0;
    }
    if(root->key==a){
        return level;
    }
    levelNode(root->left,a,level+1);
    levelNode(root->right,a,level+1);
}

标签: c++data-structures

解决方案


应该像

int levelNode(struct Node* root,int a,int level){
    int found;
    if(root==NULL){
        return 0;
    }

    if(root->key==a){
        return level;
    }

    found = levelNode(root->left,a,level+1);
    if (found != 0) return found;

    found = levelNode(root->right,a,level+1);
    if (found != 0) return found;

    return 0; 
}

推荐阅读