Check if removing an edge can split a binary tree into two equal size trees

import java.util.concurrent.atomic.AtomicBoolean;


// A category to retailer a binary tree node

class Node

    int information;

    Node left, proper;


    Node(int information)


        this.information = information;

        this.left = this.proper = null;



class Principal

    // Perform to return the full variety of nodes in a given binary tree

    public static int dimension(Node root)

        return root != null ? (1 + dimension(root.left) + dimension(root.proper)): 0;



    // Replace `consequence` to true if the dimensions of a binary tree rooted at `root`

    // or the dimensions of any of its subtrees is strictly `n/2`

    public static int checkSize(Node root, int n, AtomicBoolean consequence)



    // Perform to examine if a given binary tree could be break up into

    // two binary timber of equal dimension

    public static boolean splitTree(Node root)


        // depend the full variety of nodes within the binary tree

        int n = dimension(root);


        // if a binary tree comprises an odd variety of nodes, it can’t be evenly break up

        if ((n & 1) == 1)

            return false;



        AtomicBoolean consequence = new AtomicBoolean();

        checkSize(root, n, consequence);

        return consequence.get();



    public static void predominant(String[] args)


        Node root = new Node(1);

        root.left = new Node(2);

        root.proper = new Node(3);

        root.left.left = new Node(4);

        root.left.proper = new Node(5);

        root.proper.proper = new Node(6);


        if (splitTree(root))

            System.out.println(“The binary tree could be break up”);



            System.out.println(“The binary tree can’t be break up”);



More Posts