Consider the following type of binary trees data Tree a Lea

Consider the following type of binary trees: data Tree a = Leaf a | Node (Tree a) (Tree a) Let us say that such a tree is balanced if the number of leaves in the left and right subtree of every node differs by at most one, with leaves themselves being trivially balanced. Define a function balanced:: Tree a rightarrow Bool that decides if a binary tree is balanced or not.

Solution

Function balanced(Tree a){

}

ANS:---->>>   

static boolean balanced(Tree a) {
if (a == null) {
throw new IllegalArgumentException(\"The tree -> a must not be null\");
}
return (maximumDepth(a) - minimumDepth(a)) <= 1;
}

static int minimumDepth(Tree a) {
if (a == null) {
return 0;
}
return 1 + Math.min(minimumDepth(a.left), minimumDepth(a.right));
}


static int maximumDepth(Tree a) {
if (a == null) {
return 0;
}
return 1 + Math.max(maximumDepth(a.left), maximumDepth(a.right));
}
}

 Consider the following type of binary trees: data Tree a = Leaf a | Node (Tree a) (Tree a) Let us say that such a tree is balanced if the number of leaves in t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site