Monday, April 23, 2018

Determine the number of nodes in a binary tree

In order to find out number of nodes in a tree, we can traverse the tree using any of the traversal method - preorder, inorder and postorder and while traversing we can keep counting the nodes. Solution can be implemented using recursive approach as described earlier as well as using iterative method. In iterative method, we can use level order traversal and keep counting the nodes.
For example, number of nodes in the following binary tree is 9:

Time Complexity: O(n)

Java Recursive Solution:

public class NodeCount {
    static class Node {
        int data;
        Node left;
        Node right;

        Node(int data) {
            this.data = data;
        }
    }

    public int getNumberOfNodes(Node root){
        if(root == null){
            return 0;
        }

        return 1 + getNumberOfNodes(root.left) + getNumberOfNodes(root.right);
    }

    public static void main(String[] args) {
        //Build Tree
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        Node node7 = new Node(7);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        System.out.println("Number of nodes in tree are: " + new NodeCount().getNumberOfNodes(node1));
    }
}


No comments:

Post a Comment

Categories