public int InsertNode(ref Node T, aboutWord key) { if (T != null) { if (String.Compare(key.word, T.data.word, true) == 0) { return(0); } else if (String.Compare(key.word, T.data.word, true) < 0) { return(InsertNode(ref T.pLeft, key)); } else { return(InsertNode(ref T.pRight, key)); } } Node temp = new Node(key); if (temp == null) { return(-1); } T = temp; return(1); }
public Node insert(Node node, aboutWord key) { /* 1. Perform the normal BST insertion */ if (node == null) { return(new Node(key)); } if (String.Compare(key.word, node.data.word, true) < 0) { node.pLeft = insert(node.pLeft, key); } else if (String.Compare(key.word, node.data.word, true) > 0) { node.pRight = insert(node.pRight, key); } else // Duplicate keys not allowed { return(node); } /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.pLeft), height(node.pRight)); /* 3. Get the balance factor of this ancestor * node to check whether this node became * unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && string.Compare(key.word, node.pLeft.data.word) < 0) { return(rightRotate(node)); } // Right Right Case if (balance < -1 && string.Compare(key.word, node.pRight.data.word) > 0) { return(leftRotate(node)); } // Left Right Case if (balance > 1 && string.Compare(key.word, node.pLeft.data.word) > 0) { node.pLeft = leftRotate(node.pLeft); return(rightRotate(node)); } // Right Left Case if (balance < -1 && string.Compare(key.word, node.pRight.data.word) < 0) { node.pRight = rightRotate(node.pRight); return(leftRotate(node)); } /* return the (unchanged) node pointer */ return(node); }
//Tạo một node mới với khóa là Key, không nhánh public Node(aboutWord key) { data = key; height = 1; pLeft = pRight = null; }