Sum of all nodes in a binary tree

In a Binary Tree, our aim is to find the sum of all nodes in the Binary tree.

The sum of all node can be found using any traversal.H ere we will be using Inorder Traversal for the same.You can do this from Pre Order or PostOrder as well.

We just need to traverse the tree and maintain a sum value and keep adding each time a new value is found.

The time complexity for this in O(n)

The code is –

class Node {
    int data;
    Node left, right;

    public Node(int d) {
        data = d;
        left = right = null;
    }
    public Node() {
        data = 0;
        left = right = null;
    }
}

class BTree {
    Node root;

    /* returns sum of all nodes */
    public int sumBT(Node root) {
        if (root == null)
            return 0;
        int sum = 0;
        sum += sumBT(root.left);
        sum += root.data;
        sum += sumBT(root.right);
        return sum;
    }

    public static void main(String[] args) {
        BTree tree = new BTree();
        tree.root = new Node(10);
        tree.root.left = new Node(5);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(7);
        tree.root.left.right = new Node(5);
        tree.root.right.right = new Node(1);
        System.out.println("The sum of all nodes of tree are " + tree.sumBT(tree.root));

    }
}