【问题标题】:Recursively count children nodes in binary tree递归计算二叉树中的子节点
【发布时间】:2015-08-31 09:48:19
【问题描述】:

我的编码练习参考了它的子节点计数。 我决定使用递归,我想知道这是一种优雅的方式:

假设有一个类 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);
}

【问题讨论】:

  • 我们应该建议什么?
  • 你试过了吗?它是否为您提供了正确数量的各种树的孩子?
  • 我建议你把它改成java。

标签: java recursion binary-tree nodes


【解决方案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);
}

这是我的建议。

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2014-08-12
    • 2016-01-17
    • 2014-05-10
    • 2018-10-30
    • 1970-01-01
    • 2020-09-04
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多