简体   繁体   English

递归计算二叉树中的内部节点(父节点)

[英]Counting the inner nodes (parent nodes) in a binary tree recursively

I need to create a recursive method that takes as a parameter the root node of a binary search tree. 我需要创建一个以二进制搜索树的根节点为参数的递归方法。 This recursive method will then return the int value of the total number of inner nodes in the entire binary search tree. 然后,此递归方法将返回整个二进制搜索树中内部节点总数的int值。

This is what I have so far: 这是我到目前为止的内容:

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

Is there a better way? 有没有更好的办法? I also stuck to find a iterativ solution. 我还坚持寻找iterativ解决方案。

Here's the recursive method fixed: 这是固定的递归方法:

int countNrOfInnerNodes (Node node) {
    if(node == null) {
       return 0;
    }

    if (node.left == null && node.right == null) {
       // not an inner node !
       return 0;
    } else {
       // the number of inner nodes in the left sub-tree + the number of inner
       // nodes in the right sub-tree, plus 1 for this inner node
       return countNrOfInnerNodes(node.left) + countNrOfInnerNodes(node.right) + 1;
    }
}

Here's the iterative method: 这是迭代方法:

int countNrOfInnerNodes(Node node) {
    if (node == null)
        return 0;

    Stack<Node> nodesToCheck = new Stack<Node>();

    nodesToCheck.push(node);
    int count = 0;

    while (!nodesToCheck.isEmpty()) {
        Node checkedNode = nodesToCheck.pop();
        boolean isInnerNode = false;

        if (node.left != null) {
            isInnerNode = true;
            nodesToCheck.push(node.left);
        }

        if (node.right != null) {
            isInnerNode = true;
            nodesToCheck.push(node.right);
        }

        if (isInnerNode)
            count++;
    }

    return count;
}

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

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