235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
题目解析:
- 根据二叉搜索树的性质,只需要找到节点在p和q之间即可
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int min = Math.min(p.val, q.val), max = Math.max(p.val, q.val);
while (true) {
if (root.val < min) {
root = root.right;
} else if (root.val > max) {
root = root.left;
} else {
return root;
}
}
}
}
701. Insert into a Binary Search Tree
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
题目解析:
- 根据目标值在二叉搜索树中找到一个空位置
代码:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode node = new TreeNode(val);
if (root == null) {
return node;
}
TreeNode head = root;
while (head != null) {
if (head.val < val) {
if (head.right != null) {
head = head.right;
} else {
head.right = node;
break;
}
} else {
if (head.left != null) {
head = head.left;
} else {
head.left = node;
break;
}
}
}
return root;
}
}
450. Delete Node in a BST
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
- Search for a node to remove.
- If the node is found, delete the node.
题目解析:
- 根据BST性质找到key对应的节点,分为3种情况
- 节点为根节点
- 节点为某节点的左节点
- 节点为某节点的右节点
- 需要定义子函数用来删除二叉树树的根节点,也分为3种情况
- 该节点存在左右节点
- 该节点没有左右节点
- 该节点只存在左节点或者右节点其中一个
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode head = root, prev = null;
while (head != null) {
if (head.val < key) {
prev = head;
head = head.right;
} else if (head.val > key) {
prev = head;
head = head.left;
} else {
// head.val == key
if (prev == null) {
// head == root
return removeRoot(root);
} else if (prev.left == head) {
prev.left = removeRoot(head);
} else if (prev.right == head) {
prev.right = removeRoot(head);
}
return root;
}
}
return root;
}
public TreeNode removeRoot(TreeNode root) {
if (root.left == null && root.right == null) {
return null;
}
if (root.left != null && root.right == null) {
return root.left;
}
if (root.left == null && root.right != null) {
return root.right;
}
TreeNode left = root.left, right = root.right;
TreeNode newRoot = right;
while (right.left != null) {
right = right.left;
}
right.left = left;
return newRoot;
}
}