235. 二叉搜索树的最近公共祖先
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
if (root === null) {
return root;
}
if (root.val > p.val && root.val > q.val) {
return root.left = lowestCommonAncestor(root.left, p, q);
} else if (root.val < p.val && root.val < q.val) {
return root.right = lowestCommonAncestor(root.right, p, q);
} else {
return root;
}
};
701. 二叉搜索树中的插入操作
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
if (root === null) {
return new TreeNode(val);
}
if (root.val > val) {
root.left = insertIntoBST(root.left, val);
}
if (root.val < val) {
root.right = insertIntoBST(root.right, val)
}
return root;
};
450. 删除二叉搜索树中的节点
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
if (root === null) {
return null;
};
if (root.val === key) {
if (root.left === null && root.right === null) {
return null;
}
if (root.left === null && root.right !== null) {
return root.right;
}
if (root.left !== null && root.right === null) {
return root.left;
}
if (root.left !== null && root.right !== null) {
let cur = root.right;
while (cur.left) {
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
if (root.val < key) {
root.right = deleteNode(root.right, key);
}
if (root.val > key) {
root.left = deleteNode(root.left, key);
}
return root;
};