Ask Question
15 March, 04:06

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.

+1
Answers (1)
  1. 15 March, 05:42
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers