Ask Question
28 May, 05:18

A perfect binary tree is a complete binary tree with all levels fully filled. Add a method in the BST class to return true if the tree is a perfect binary tree.

+3
Answers (1)
  1. 28 May, 05:47
    0
    class BST {

    static class Node

    {

    int val;

    Node left, right;

    }

    static boolean checkPerfectBT (Node node, int h, int d)

    {

    if (node = = null)

    return true;

    if (node. left = = null && node. right = = null)

    {

    if (h==d+1)

    return true;

    else

    return false;

    }

    if (node. left = = null || node. right= = null)

    return false;

    return checkPerfectBT (node. left, h, d+1) && checkPerfectBT (node. right, h, d+1);

    }

    static int height (Node node)

    {

    int dep = 0;

    while (node! = null)

    {

    node = node. right;

    dep=dep+1;

    }

    return dep;

    }

    static boolean isPerfectBT (Node node)

    {

    int h = height (node);

    return checkPerfectBT (node, h, 0);

    }

    static Node addNode (int x)

    {

    Node node = new Node ();

    node. val = x;

    node. right = null;

    node. left = null;

    return node;

    }

    public static void main (String args[])

    {

    int i, j, k;

    Node node = null;

    node = addNode (34);

    node. left = addNode (2);

    node. right = addNode (322);

    node. left. left = addNode (21);

    node. left. right = addNode (23);

    node. right. left = addNode (37);

    node. right. right = addNode (54);

    if (isPerfectBT (node) = = true)

    System. out. println ("This is a Perfect Binary tree");

    else

    System. out. println ("This is Not a perfect Binary Tree");

    }

    }

    Explanation:

    Calculate the depth of BST by using a while loop until it reaches a null value. In the addNode method, make an object of Node class. In the main method, pass the values to addNode method. Finally display the relevant message to show if it's Perfect or not.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “A perfect binary tree is a complete binary tree with all levels fully filled. Add a method in the BST class to return true if the tree is a ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers