Balanced Binary Tree
Execution time limit is 1 second
Runtime memory usage limit is 128 megabytes
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.
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 (1 ≤ n ≤ 100). 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.
Examples
Input #1
Answer #1
Submissions 516
Acceptance rate 43%