Untitled

 avatar
unknown
plain_text
a month ago
1.0 kB
2
Indexable
// Iterative Search in BST
public TreeNode searchBST(TreeNode root, int key) {
    while (root != null) {
        if (key == root.val) {
            return root; // Key found
        } else if (key < root.val) {
            root = root.left; // Go to the left subtree
        } else {
            root = root.right; // Go to the right subtree
        }
    }
    return null; // Key not found
}

// Iterative Insert in BST
public TreeNode insertIntoBST(TreeNode root, int key) {
    if (root == null) {
        return new TreeNode(key); // Empty tree case
    }
    TreeNode parent = null, current = root;
    while (current != null) {
        parent = current;
        if (key < current.val) {
            current = current.left;
        } else {
            current = current.right;
        }
    }
    // Attach the new node
    if (key < parent.val) {
        parent.left = new TreeNode(key);
    } else {
        parent.right = new TreeNode(key);
    }
    return root;
}
Leave a Comment