【问题标题】:How to count non-leaf nodes in a binary search tree?如何计算二叉搜索树中的非叶节点?
【发布时间】:2018-12-05 21:09:34
【问题描述】:

我正在用我的代码发布新问题。我正在尝试计算二叉搜索树的非叶节点。我正在创建非叶方法,然后尝试在测试类中调用它。有人能帮我吗?代码如下:

public class BST {
    private Node<Integer> root;

    public BST() {
        root = null;
    }

    public boolean insert(Integer i) {
        Node<Integer> parent = root, child = root;
        boolean gLeft = false;

        while (child != null && i.compareTo(child.data) != 0) {
            parent = child;
            if (i.compareTo(child.data) < 0) {
                child = child.left;
                gLeft = true;
            } else {
                child = child.right;
                gLeft = false;
            }
        }

        if (child != null)
            return false;
        else {
            Node<Integer> leaf = new Node<Integer>(i);
            if (parent == null)
                root = leaf;
            else if (gLeft)
                parent.left = leaf;
            else
                parent.right = leaf;
            return true;
        }
    }

    public boolean find(Integer i) {
        Node<Integer> n = root;
        boolean found = false;

        while (n != null && !found) {
            int comp = i.compareTo(n.data);
            if (comp == 0)
                found = true;
            else if (comp < 0)
                n = n.left;
            else
                n = n.right;
        }

        return found;
    }

    public int nonleaf() {
        int count = 0;
        Node<Integer> parent = root;

        if (parent == null)
            return 0;
        if (parent.left == null && parent.right == null)
            return 1;
    }

}

class Node<T> {
    T data;
    Node<T> left, right;

    Node(T o) {
        data = o;
        left = right = null;
    }
}

【问题讨论】:

    标签: java binary-search-tree


    【解决方案1】:

    如果您只对非叶节点的计数感兴趣,那么您可以遍历树一次并保持一个计数。每当您遇到一个节点时,它具有左节点或右节点增量计数。

    【讨论】:

    【解决方案2】:

    您可以使用以下函数计算二叉树的非叶节点数。

    int countNonLeafNodes(Node root)
    { 
        if (root == null || (root.left == null &&  
                             root.right == null)) 
            return 0; 
        return 1 + countNonLeafNodes(root.left) +  
                   countNonLeafNodes(root.right); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多