简体   繁体   中英

count number of level in Binary Tree

I'm trying to count number of node in specific level using recursive "Java". I tried below code but the problem is when i pass level which is not exit empty in tree for example there is 4 level in the tree when I pass 5 it keep counting element , How can I fix it ? any help appreciated .

private int countNodeLevel(int level,Node<E> n) 
{
    Node<E> curr=root;
    
    if(curr == null) {
        return 0;
    } 
    if(level == 0) {
        return 1;
    }
                
    return ( countNodeLevel( level - 1,n.leftChild)+countNodeLevel(level - 1, n.rightChild));
}
private int countNodeLevel(int level, Node<E> n) {
    if (n == null) {
        return 0;
    } 
    if (level <= 0) {
        return 0;
    }
               
    return 1
        + countNodeLevel(level - 1, n.leftChild)
        + countNodeLevel(level - 1, n.rightChild);
}

Level 0 seems more logical to return 0. For a node there is 1 + left + right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM