Here is a simple and short Java program to find the sum of all nodes in a binary tree using recursion:
- ✅ Java Code: Sum of All Nodes (Minimal Version)
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
}
}
public class SumOfNodes {
int sum(Node node) {
if (node == null) return 0;
return node.data + sum(node.left) + sum(node.right);
}
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.left.left = new Node(2);
root.right.right = new Node(8);
SumOfNodes tree = new SumOfNodes();
System.out.println(“Sum of all nodes: ” + tree.sum(root));
}
}
📌 Output:
Sum of all nodes: 40
💡 Explanation:
Recursively add node.data with sum of left and right subtrees.
If node is null, return 0.