Sum of numbers in a tree#1185

Sum of numbers in a tree

1 second
122.174 megabytes
Very easy

Given an array of integers. Build a Binary Search Tree (BST) from these numbers. If the inserted value is equal to the current node, insert it into the right subtree.

Implement the method Sum that returns the sum of the numbers at all nodes of the tree.

prb7463.gif

Write code according to the following interface:

class TreeNode
{
public:
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Tree
{
public:
  TreeNode *head;
  Tree() : head(NULL) {};

  void Insert(int val); // Insert the number val into the BST
  int Sum(void); // Return the sum of the numbers at all nodes
};

You may create and use additional methods if needed.

Input

The first line contains the number (1 \le n \le 100). The second line contains integers.

Output

Build the Binary Search Tree from the input data. Output the sum of the numbers at all nodes of the tree.

Examples

Example 1

Loading
Loading