Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++. Test if a Tree is Balanced Use the given Tree class and implement a functio

ID: 3604703 • Letter: C

Question

C++.

Test if a Tree is Balanced

Use the given Tree class and implement a function to test if the binary tree is balanced or not.

An empty tree is height-balanced. A non-empty binary tree T is balanced if:

1) Left subtree of T is balanced

2) Right subtree of T is balanced

3) The difference between heights of left subtree and right subtree is not more than 1.

#include <iostream>
using namespace std;

template<class ItemType>
class Tree {
private:
Tree<ItemType> * left;
Tree<ItemType> * right;
ItemType data;

public:
Tree(ItemType _data){left = NULL; right = NULL; data = _data;}
void insert(ItemType _data){
if( _data > data){
if(right == NULL){
right = new Tree(_data);
}else{
right->insert(_data);
}
}else{
if(left == NULL){
left = new Tree(_data);
}else{
left->insert(_data);
}
}
}
  
bool isBalanced(){
// Implement this Function
}

};


int main() {
return 0;
}

Explanation / Answer


bool IsBalanced()
{
   if(Height(root) == -1)
   {
      return false;
   }
   else
   {
      return true;
   }
}

int Height(Node root)
{
if(root == null)
   return 0;

// if left is balanaced
int lchild = Height(root.left);
if(lchild == -1) return -1; // Not Balanced

// if right is balanaced
int rchild = Height(root.right);
if(rchild == -1) return -1; // Not Balanced

// Check if current node is balanced
int Check_heigth = lchild - rchild;

if(Math.abs(Check_heigth) > 1)
   return -1; // not balanaced
else
   return Math.max(lchild, rchild) + 1; // Return Height
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote