counting number of leaf nodes in binary tree

瘦欲@ 提交于 2019-11-30 16:57:26

问题


I want to count the no of leaf nodes: Note:Cannot use global/class level variable I implmeted following algo, and it works fine.But i want method signature to be

countLeaves(Node node)

I know that i can overload methds and call the 2 args method sig from 1 args, but dont want to do so.Can anyone suggest any other method?

int countLeaves(Node node,int count){
        if(node==null)
            return 0;

        if(node.left==null && node.right==null){
            return 1+count;
        }else{
            int lc = countLeaves(node.left, count);
            int total = countLeaves(node.right, lc);
            return total;
        }
    }

回答1:


int countLeaves(Node node){
  if( node == null )
    return 0;
  if( node.left == null && node.right == null ) {
    return 1;
  } else {
    return countLeaves(node.left) + countLeaves(node.right);
  }
}

You are doing the same thing as before but instead of holding the current count as we go, we simply say return the result of the sum of the left and right node. These in turn recurse down till they hit the basecases.




回答2:


You don't need to pass count down the call stack, only up from:

int countLeaves(Node node)
{
    if(node==null) {
        return 0;
    }
    if(node.left==null && node.right==null) {
        return 1;
    }
    return countLeaves(node.left) + countLeaves(node.right);
}



回答3:


We can apply two approaches , one is Recursive and other one is iterative(queue based implementation ) .Here i am going to explain both methods.

Recursive Solution

int count_leaf(Node node)
{
 if(node==NULL)
  return 0;
  if(node->left==NULL && node->right==NULL)
  return 1;
   return count_leaf(node->left)+count_leaf(node->right);
}

Second Method is Iterative(Queue based implementation ) , idea is taken from level order traversal of a tree.

int count_leaf(Node root)
{
int count=0;
  if(root==NULL)
    return 0;

  queue<Node *> myqueue;
  myqueue.push(root);

  while(!myqueue.empty())
{
  Node temp;
   temp=myqueue.top();   //Take the front element of queue 
   myqueue.pop();        //remove the front element of queue
  if(temp->left==NULL && temp->right==NULL)
   count++;
   if(temp->left)
    myqueue.push(temp->left);
   if(temp->right)
   myqueue.push(temp->right);
}
return count;
}

I hope these solutions will help you.




回答4:


Fill in ??? part yourself.

int countLeaves(Node node){
    if (node==null)
        return 0;

    if (node.left==null && node.right==null){
        return 1;
    } else {
        int lc = countLeaves(node.left);
        int rc = countLeaves(node.right);
        return ???;
    }
}



回答5:


As I am still unit testing this implementation, no promises of bug-free operation are made. If there are particular issues with the implementation, I am happy to receive the feedback.

Initially, I am receiving favorable results:

#region CountNode utility
private int CountNode(Node node, Direction d) {
    Func<Direction, Node> leaf = (dir) => {
        return dir == Direction.Left ? node.Left : node.Right;
    };

    var done = leaf(d) == null;
    var root = node;
    var stack = new Stack<Node>( );
    var count = 0;

    while(!done) {
        if (node != null) {
            stack.Push(node);
            node = leaf(d);
        }
        else {
            if(stack.Count > 0) {
                node = stack.Pop( );
                //  back to root, time to quit
                if(node == root) {
                    done = true;
                    continue;
                }

                //  count nodes when popped
                ++count;

                //  flip direction
                var flip = d == Direction.Left ? Direction.Right : Direction.Left;
                //  get the leaf node
                node = leaf(flip);
            }
            else {
                done = true;
            }
        }
    }

    return count;
}
#endregion

Usage:

var actLeftCount = CountNode(root, Direction.Left);
var actRightCount = CountNode(root, Direction.Right);

This has the particular advantage of giving counting only the nodes on the Left. I can pass any node into the method and receive statistics for the same.




回答6:


Same as in the first comment.

 int getLeafNodeCount(Node<T> node) {
        if(node == null) {
             return 0;
        } 
        if (node.leftChild == null && node.rightChild == null) {
             return 1;
        } else {
             return getLeafNodeCount(node.leftChild) + getLeafNodeCount(node.rightChild);
        }
   }



回答7:


public int getLeafsCount(BSTNode<T> node, int count) {
    if(node == null || node.getData() == null){
        return count;
    }
    else if(isLeaf(node)){
        return ++count;
    }else{  
        int leafsLeft =  getLeafsCount((BSTNode<T>) node.getLeft(), count);
        int leafsCount = getLeafsCount((BSTNode<T>) node.getRight(), leafsLeft);

        return leafsCount;
    }

}


来源:https://stackoverflow.com/questions/5949882/counting-number-of-leaf-nodes-in-binary-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!