我需要实现AVL树inserion。
该算法可在https://en.wikipedia.org/wiki/AVL_tree找到。
以下是我的完整代码。
rotateLeft被调用两次但是如果逻辑工作可能它只应该被调用一次以便跟随输入:
2-3(根)-4(右)-5(右)-6(右)
我应该得到什么:
2(BF = 0)3(BF = -1)4(BF = 0)5(BF = 0)6(BF = 0)
3(BF = -1)2(BF = 0)5(BF = 0)4(BF = 0)6(BF = 0)
我得到的是什么:
2(BF = 0)3(BF = -2)3(BF = 0)4(BF = -1)4(BF = 0)5(BF = 0)6(BF = 0)
3(BF = -2)2(BF = 0)4(BF = -1)3(BF = 0)5(BF = 0)4(BF = 0)6(BF = 0)
注意:这是来自hackerrank的问题,可以在https://www.hackerrank.com/challenges/self-balancing-tree
找到/* Class node is defined as :
class Node
int val; //Value
int ht; //Height
Node left; //Left child
Node right; //Right child
*/
static Node insert(Node root,int val)
{
Node newNode = new Node();
newNode.val = val;
insertT(root, val);
//inOrder(root);
return root;
}
static int insertT(Node root,int val){
Node newNode = new Node();
Node tempNode = root;
newNode.val = val;
int bf = 0;
int pbf = 0 ;
if (tempNode.left==null && tempNode.val>val){
tempNode.left = newNode;
bf = setHt(tempNode.left) - setHt(tempNode.right);
return bf;
}
if (tempNode.right==null && tempNode.val<val){
tempNode.right = newNode;
bf = setHt(tempNode.left) - setHt(tempNode.right);
return bf;
}
if (tempNode.left!=null && tempNode.val>val){
pbf = insertT(tempNode.left, val);
bf = setHt(tempNode.left) - setHt(tempNode.right);
if (bf==2) {
if (pbf==-1){
tempNode.left = rotateLeft(tempNode.left, tempNode.left.right);
}
tempNode = rotateRight(tempNode,tempNode.left);
}
bf = setHt(tempNode.left) - setHt(tempNode.right);
return bf;
}
if (tempNode.right!=null && tempNode.val<val){
pbf = insertT(tempNode.right, val);
bf = setHt(tempNode.left) - setHt(tempNode.right);
if (bf==-2) {
if (pbf==1){
tempNode.right = rotateRight(tempNode.right, tempNode.right.left);
}
tempNode = rotateLeft(tempNode,tempNode.right);
}
bf = setHt(tempNode.left) - setHt(tempNode.right);
return bf;
}
return bf;
}
static void inOrder(Node root) {
if (root.left!=null) inOrder(root.left);
System.out.print(root.val + ", ");
if (root.right!=null) inOrder(root.right);
}
static int setHt(Node root) {
if(root!=null) {
root.ht = Math.max(setHt(root.left),setHt(root.right)) + 1;
return root.ht;
}
return -1;
}
static Node rotateRight(Node root, Node leftChild) {
Node tempNode = new Node();
tempNode.val = root.val;
tempNode.ht = root.ht;
leftChild.right = tempNode;
root = leftChild;
setHt(root);
//System.out.println("rr");
//inOrder(root);
return root;
}
static Node rotateLeft(Node root, Node rightChild) {
Node tempNode = new Node();
tempNode.val = root.val;
tempNode.ht = root.ht;
rightChild.left = tempNode;
root = rightChild;
setHt(root);
//System.out.println("rl");
//inOrder(root);
return root;
}