简体   繁体   中英

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);
}
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.

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