Sum of Binary Tree in Java

 Sum of Binary Tree in Java


To calculate the sum of all the values in a binary tree in Java, you can use a recursive traversal to visit each node in the tree and add its value to the total sum.



Here is an example of how you might write a Java method that calculates the sum of a binary tree:


class BinaryTreeSum {

  public static int sum(TreeNode node) {

    if (node == null) {

      return 0;

    }

    return node.value + sum(node.left) + sum(node.right);

  }

}

This method uses a recursive approach to traverse the tree in a depth-first manner, visiting each node and adding its value to the total sum.

To use this method, you will need to have a tree node class defined, such as the one shown below:

class TreeNode {
  int value;
  TreeNode left;
  TreeNode right;

  public TreeNode(int value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

You can then call the sum method on the root node of the tree to calculate the sum of all the values in the tree. For example:

TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);

int sum = BinaryTreeSum.sum(root);
System.out.println("Sum: " + sum); // Outputs "Sum: 6"

Post a Comment

0 Comments