eolymp
bolt
Try our new interface for solving problems
Problems

Balanced Binary Tree

Balanced Binary Tree

Given an array of integers. Create a Binary Search Tree from these numbers. If the inserted value equals to the current node, insert it to the right subtree.

Write a method IsBalanced that determine if it is height-balanced. A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

prb7463.gif

Write the code according to the next interface:

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

class Tree
{
public:
  TreeNode *head;
  Tree() : head(NULL) {};
  void Insert(int val); // Insert number val into Binary Search Tree
  int IsBalanced(void); // return 1 if Binary Search Tree is balanced and 0 otherwise
};
// Java
class TreeNode
{
  int val;
  TreeNode left, right;
  TreeNode(int x)
  {
    val = x;
    left = right = null;
  }
}

class Tree
{
  TreeNode head;
  Tree();
  void Insert(int val); // Insert number val into Binary Search Tree
  int IsBalanced(); // return 1 if Binary Search Tree is balanced and 0 otherwise
}

You can create (use) additional methods if needed.

Input

The first line contains number n (1n100). The second line contains n integers.

Output

Create the Binary Search Tree from input data. Print 1 if it is height-balanced and 0 otherwise.

Time limit 1 second
Memory limit 128 MiB
Input example #1
6
14 9 1 14 20 13
Output example #1
1
Author Mykhailo Medvediev
Source C++ / Java Language