Delete Node in a BST 二叉查詢樹的查詢、插入和刪除 - Java實現
阿新 • • 發佈:2018-11-16
https://leetcode.com/problems/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.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
解題思路:
1. 根據BST的特性,找到需要刪除的node。
2. 如果node左右子樹都是空的,直接返回null。
3. 如果左子樹為空,那麼直接用右側子樹代替node。
4. 如果右側子樹為空,那麼直接用左子樹代替node。
5. 如果左右子樹都不是空,有些麻煩。首先要去node的右子樹中找到最小的那個節點,也就是右子樹中最左側的節點。
然後用它去替代node,並且把node的父節點的left置為空。
遞迴的時候,什麼時候直接return,什麼時候root.left = 呼叫遞迴,需要值得注意。
這個關係到,總是疑惑,刪除本node,那麼如何將父節點的left(right)置為null?需要好好理解。
詳細可以看二叉查詢樹的查詢、插入和刪除 - Java實現。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode deleteNode(TreeNode root, int key) { if (root == null) { return root; } if (root.val > key) { root.left = deleteNode(root.left, key); } else if (root.val < key) { root.right = deleteNode(root.right, key); } else { if (root.right == null) { return root.left; } else if (root.left == null) { return root.right; } else { TreeNode temp = root; root = findMin(root.right); root.right = deleteMin(temp.right); root.left = temp.left; } } return root; } private TreeNode findMin(TreeNode root) { if (root.left != null) { return findMin(root.left); } return root; } private TreeNode deleteMin(TreeNode root) { if (root.left != null) { root.left = deleteMin(root.left); } else { return root.right; } return root; } }