在二进制搜索树中计算具有2个子节点的节点数的方法

时间:2012-05-25 14:40:03

标签: java binary-search-tree tree-traversal

这是我能提出的最好但它仍然不起作用,因为它返回1,即使有多个节点有两个孩子。

int countTwoChildren(Node node)
{
    if(node==null) {
        return 0;
    }
    if(node.left!=null && node.right!=null) {
        return 1;
    }
    return countTwoChildren(node.left) + countTwoChildren(node.right);
}

任何人都可以在上面的代码中找到任何错误吗?

6 个答案:

答案 0 :(得分:2)

缺少一件小事:

int countTwoChildren(Node node)
{
    if(node==null) {
        return 0;
    }
    if(node.left!=null && node.right!=null) {
        return 1 + countTwoChildren(node.left) + countTwoChildren(node.right);
    }
    return countTwoChildren(node.left) + countTwoChildren(node.right);
}

答案 1 :(得分:0)

您的问题是,如果某个节点有两个子节点,则不会降低其自己的子节点。您应该更改支票的顺序:

int countTwoChildren(Node node)
{
    int nc;

    if(node==null) {
        return 0;
    }

    nc = countTwoChildren(node.left) + countTwoChildren(node.right);
    if(node.left!=null && node.right!=null) {
        return nc++;
    }

    return nc;
}

当然,这整件事可以写成一行:

int countTwoChildren(Node node)
{
    return (node == null
            ? 0
            : countTwoChildren(node.left) + countTwoChildren(node.right) +
              (node.left!=null && node.right!=null ? 1 : 0));
}

答案 2 :(得分:0)

int countTwoChildren(Node node)
{
    if (node == null)
        return 0;
    int here  = node.left != null && node.right != null ? 1 : 0;
    int left  = countTwoChildren(node.left);
    int right = countTwoChildren(node.right);
    return here + left + right;
}

答案 3 :(得分:0)

你所有遗失的是其他的,比如你有一个if语句,检查节点是否同时具有左和右右链接不为空,但如果它为空,

您只需添加其他内容:

if(node.left!=null && node.right!=null) {
    return 1 + countTwoChildren(node.left) + countTwoChildren(node.right);
}else{
   return countTwoChildren(node.left) + countTwoChildren(node.right);
  }

当你说如果左边和右边的节点都不为空它只返回1时你出错了,你应该继续遍历树以通过递归地分别为左节点和右节点调用countTwoChildren来找到另一个节点。

答案 4 :(得分:0)

如果root具有左右节点,那么你的程序将在第一次终止,因此它将返回1,并且不会进行递归调用。这是解决方案,希望有所帮助

public static int numberOfFullNode(TreeDemo root){
        if(root==null)
            return 0;
        else if(root.left!=null && root.right!=null)
            return 1+numberOfFullNode(root.left)+numberOfFullNode(root.right);
        else return 0;
    }

答案 5 :(得分:0)

这个问题已经得到了很好的回答,只需为同一个问题分享迭代解决方案:

public static int findTheNumberOfFullNodesIterative(BTNode root) {

    int noOfFullNodes = 0;
    if (root == null) {
        return 0;
    }
    Queue<BTNode> q = new LinkedList<>();
    q.offer(root);

    while (!q.isEmpty()) {
        BTNode temp = q.poll();
        if (temp.getLeft() != null && temp.getRight() != null) {
            noOfFullNodes++;

        }
        if (temp.getLeft() != null) {
            q.offer(temp.getLeft());
        }
        if (temp.getRight() != null) {
            q.offer(temp.getRight());
        }
    }
    return noOfFullNodes;
}