A binary tree is balanced if every node in the tree is such that the heights of its left and right subtrees do not differ by more than one. Complete the pseudo-code method isBalanced which determines if a binary tree is balanced. The function returns a value of -1 if the tree is not balanced, otherwise it returns the height of the tree. Add comments to explain what your code segment is doing. The following definition of a node in the tree is used. class BinaryNode { int element; BinaryNode left; BinaryNode right; } Complete the method below: int isBalanced (BinaryNode t) { int leftCount=0; int rightCount=0; if (t == null) //empty tree, height is 0 return 0; if ((t.left== null) and (t.right== null) return 0; else { . . . . . . . . . } }
A binary tree is balanced if every node in the tree is such that the heights of its left and right subtrees do not differ by more than one. Complete the pseudo-code method isBalanced which determines if a binary tree is balanced. The function returns a value of -1 if the tree is not balanced, otherwise it returns the height of the tree. Add comments to explain what your code segment is doing.
The following definition of a node in the tree is used.
class BinaryNode {
int element;
BinaryNode left;
BinaryNode right;
}
Complete the method below:
int isBalanced (BinaryNode t) {
int leftCount=0;
int rightCount=0;
if (t == null) //empty tree, height is 0
return 0;
if ((t.left== null) and (t.right== null)
return 0;
else {
. . .
. . .
. . .
}
}
Step by step
Solved in 2 steps