递归计算二叉树中的子节点

Recursively count children nodes in binary tree

我的编码练习给出了对其子节点计数的引用。 我决定使用递归,我想知道这是不是一种优雅的方式:

假设有 class 个节点代表树中的每个节点:

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

这是我的建议。