450. 删除二叉搜索树中的节点
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
一般来说,删除节点可分为两个步骤:
- 首先找到需要删除的节点;
- 如果找到了,删除它。
说明: 要求算法时间复杂度为 O(h),h 为树的高度。
示例:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。
一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。
5
/ \
4 6
/ \
2 7
另一个正确答案是 [5,2,6,null,4,null,7]。
5
/ \
2 6
\ \
4 7
package Solution450;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
package Solution450;
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
// Return if the tree is empty
if (root == null)
return root;
// Find the node to be deleted
if (key < root.val)
root.left = deleteNode(root.left, key);
else if (key > root.val)
root.right = deleteNode(root.right, key);
else {
// If the node is with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// If the node has two children
// Place the inorder successor in position of the node to be deleted
root.val = minValue(root.right);
// Delete the inorder successor
root.right = deleteNode(root.right, root.val);
}
return root;
}
// Find the inorder successor
int minValue(TreeNode root) {
int minv = root.val;
while (root.left != null) {
minv = root.left.val;
root = root.left;
}
return minv;
}
void inOrder(TreeNode root) {
if (root != null) {
inOrder(root.left);
System.out.println(root.val);
inOrder(root.right);
}
}
public static void main(String[] args) {
Solution sol = new Solution();
TreeNode first = new TreeNode(4);
first.left = new TreeNode(2);
first.right = new TreeNode(7);
first.left.left = new TreeNode(1);
first.left.right = new TreeNode(3);
sol.inOrder(first);
System.out.println(sol.deleteNode(first, 2));
sol.inOrder(first);
}
}
还没有评论,来说两句吧...