Hi, I wrote Insert Function, but I am not getting the proper output. I am not able to figure out what’s wrong with my code. ( Literally wasted 2 days on this thing
)
Really will appreciate the help
Thank you
// insertNode
private Node insertNode(Node node, int val)
{
if (node == null)
{
return new Node(val);
} else if (val <= node.data)
{
node.left = insertNode(node.left, val);
} else
{
node.right = insertNode(node.right, val);
}
int balanceHeight = checkBalance(node.left, node.right);
if (balanceHeight > 1)
{
// unbalanced in left tree
if (node.left.left.height >= root.left.right.height)
node = rightRotate(node);// LL Condition
else
{
// LR Condition
node.left=leftRotate(node.left);
node=rightRotate(node);
}
} else if (balanceHeight < -1)
{
// unbalanced in right tree
if (node.right.left.height <= root.right.right.height)
node=rightRotate(node);// RR COndition
else
{
// RL condition
node.right = rightRotate(node.right);
node= leftRotate(node);
}
}
node.height = calculateHeight(node);
return node;
}
// check balance
private int checkBalance(Node left, Node right)
{
if (left == null && right == null)
return 0;
else if (left == null)
return -1 - right.height;
else if (right == null)
return left.height + 1;
else
return left.height - right.height;
}
// calculate height
private int calculateHeight(Node node)
{
if (node == null)
return 0;
else
{
int leftHeight = node.left != null ? node.left.height : -1;
int rightHeight = node.right != null ? node.right.height : -1;
int maxfromLeftRight = Math.max(leftHeight, rightHeight);
return 1 + maxfromLeftRight;
}
}
// left rotate
private Node leftRotate(Node node)
{
Node newRoot = node.right;
node.right = node.right.left;
newRoot.left = node;
node.height = calculateHeight(node);
newRoot.height = calculateHeight(newRoot);
return newRoot;
}
// right rotate
private Node rightRotate(Node node)
{
Node newRoot = node.left;
node.left = node.left.right;
newRoot.right = node;
node.height = calculateHeight(node);
newRoot.height = calculateHeight(newRoot);
return newRoot;
}