Question:
How to check whether all leaves are at the same level using Java

Summary

This Java code provides methods to determine whether the provided binary tree satisfies a given condition. It also defines a solution class.


Assuming here using two methods ‘check’, and traverse and an integer ‘data’.


Solution

//User function Template for Java


/* A Binary Tree node

class Node

{

    int data;

    Node left, right;


    Node(int item)

    {

        data = item;

        left = right = null;

    }

}

*/


class Solution

{

    HashSet<Integer> hs = new HashSet<Integer>();

    boolean traverse(Node root, int k)

    {

        if(root == null)

        {

            return true;

        }

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

        {

            return (hs.isEmpty()? hs.add(k) : (!hs.add(k)));

        }

        

        return traverse(root.left,k+1) && traverse(root.right,k+1);

    }

    boolean check(Node root)

    {

// Your code here

return traverse(root,0);

    }

}


Explanation

  • It has a HashSet called his that is used to store integers.

  • The binary tree is traversed recursively by its traverse method.

  • It has an additional method check that attempts to verify the binary tree at that point.

  • It takes two parameters: root, which is the current node being traversed, and k, which an integer the root is null, it returns true, indicating that the current subtree is valid.


Answered by:> >nithinraajjp

Credit:> >GeekforGeeks


Suggested blogs:

>How to detect whether the linked list has a loop using Java

>How to determine the number of valid groupings for a string using Java

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers