Google News
logo
Java program to find the sum of all the nodes of a binary tree
In the following example of Java program to find the sum of all the nodes of a binary tree :
Program :
public class BinaryTree {
    Node root;
 
    static class Node {
        int data;
        Node left, right;
 
        Node(int value) {
            data = value;
            left = right = null;
        }
    }
 
    // Function to find the sum of all nodes of a binary tree
    public int sumNodes(Node node) {
        if (node == null)
            return 0;
        return (node.data + sumNodes(node.left) + sumNodes(node.right));
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(10);
        tree.root.left = new Node(20);
        tree.root.right = new Node(30);
        tree.root.left.left = new Node(40);
        tree.root.left.right = new Node(50);
        tree.root.right.left = new Node(60);
        tree.root.right.right = new Node(70);
 
        int sum = tree.sumNodes(tree.root);
        System.out.println("Sum of all nodes of the binary tree is " + sum);
    }
}
Output :
Sum of all nodes of the binary tree is 280
In this program, we have created a class called BinaryTree which contains a static inner class called Node to represent a node of the binary tree. We have defined a function called sumNodes() which recursively traverses the binary tree and returns the sum of all the nodes in it. In the main() function, we have created a binary tree and called the sumNodes() function to find the sum of all its nodes.