Antea
Antea

Reputation: 187

Recursively count children nodes in binary tree

My coding exercise is given the reference to the node count its children. I decided to use recursion, and I was wondering is this a elegant way to do this:

Let's assume there is class Node which represents every node in the tree:

public Node {
  int data:
  Node left;
  Node right;
}


int countChildren(Node head) {
    if(head==null) return 0;
    return countChildren(head.left)+countChildren(head.right)+ 
            ((head.left==null)?0:1) + ((head.right==null)?0:1);
}

Upvotes: 0

Views: 2972

Answers (1)

Rich Sala
Rich Sala

Reputation: 93

public Node {
  int data:
  Node left;
  Node right;
}


int countChildren(Node head) {
    if(head==null) return 0;
    return ((head.left == null) ? 0 : countChildren(head.left) + 1) + ((head.right == null) ? 0 : countChildren(head.right) + 1);
}

This is my suggestion.

Upvotes: 2

Related Questions