Question
Answer and Explanation
To sum the values in a binary tree using a recursive method in Java, you can traverse the tree and accumulate the node values. Here's how you can do it:
1. Define the Binary Tree Node Structure:
- You'll need a `Node` class that represents a node in the binary tree. This class typically contains data (the node's value) and references to the left and right child nodes.
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
2. Implement the Recursive Sum Method:
- Write a recursive method that accepts a `Node` as input and returns the sum of all the node values in the subtree rooted at that node. The base case for the recursion is when the node is null; in this case, the method should return 0. In the recursive step, the method should sum the node's data with the sum of the left and right subtrees.
public class BinaryTreeSum {
public static int sumTree(Node root) {
if (root == null) {
return 0; // Base case: empty subtree
}
return root.data + sumTree(root.left) + sumTree(root.right); // Recursive step
}
public static void main(String[] args) {
// Construct a sample binary tree
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
int totalSum = sumTree(root);
System.out.println("Sum of all nodes in the tree: " + totalSum); // Output: 15
}
}
3. Example Usage:
- The main
method constructs a simple binary tree and calls the sumTree
method. The result is then printed to the console.
4. Explanation:
- The `sumTree` method recursively traverses the binary tree. For each node, it adds its value to the sum, obtained by recursively summing the values of its left and right subtrees. The recursion terminates when it encounters null nodes. This approach ensures all the nodes are visited and their values are correctly accumulated.
This method provides a clean and concise way to sum the values in a binary tree using recursion in Java. This example also includes how to create a simple binary tree and call the sumTree method.