繁体   English   中英

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

[英]Recursively count children nodes in binary tree

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

让我们假设有一个类 Node 代表树中的每个节点:

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

这是我的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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