简体   繁体   中英

How to count non-leaf nodes in a binary search tree?

I am posting new question with my code. I am trying to count the non-leaf nodes of a binary search tree. I am creating the non-leaf method and then I am trying to call it in a test class. Can someone help me? Here is the code:

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

If you are interested in only count of non-leaf node then you can traverse tree once and maintain one count. whenever you encounter a node such that it has either left or right node increment count.

You can use the following function to count number of non-leaf nodes of binary tree.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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