In: Computer Science
java.
Consider a binary tree with integer values in its nodes, implement a method that returns the sum of the values contained in all of the nodes of the binary tree with root n.Hint: use recursion.
ANSWER:-
class BinaryTreeSum
{
static class Node
{
int data;
Node left, right;
}
/* utility that allocates a new
Node with the given key */
static Node newNode(int key)
{
Node node = new Node();
node.data = key;
node.left = node.right = null;
return (node);
}
/* Function to find sum
of all the elements*/
static int Recursive_Sum(Node root) // your required recursive
function
{
if (root == null)
return 0;
return (root.data + Recursive_Sum(root.left) +
Recursive_Sum(root.right));
}
// Driver Code
public static void main(String args[])
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
int sum = Recursive_Sum(root);
System.out.println("Sum of all the elements is: " + sum);
}
}
OUTPUT:-
// If any doubt please comment