Leetcode 450.删除二叉搜索树中的结点
原题连接:
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.
Example 1:
Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7] Explanation: 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. Please notice that another valid answer is [5,2,6,null,4,null,7] and its also accepted.
Example 2:
Input: root = [5,3,6,2,4,null,7], key = 0 Output: [5,3,6,2,4,null,7] Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0 Output: []
Constraints:
-
The number of nodes in the tree is in the range [0, 104]. -105 <= Node.val <= 105 Each node has a unique value. root is a valid binary search tree. -105 <= key <= 105
做法一:递归
BST的左右子树也都是BST,因此常考虑用递归来解题
思路:
空树就返回空 根据BST性质,比root小就递归左子树,比root大就递归右子树 如果root就是key:
-
如果没有左右孩子,直接删除 只有左孩子或右孩子,删除root,并用左孩子或右孩子代替root的位置 左右孩子都有,则找到比root大的最小节点successor(右子树的最左边),在右子树中将successor删除后,让successor来代替root的位置
c++代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { // 如果是空树, 返回空 if(root == nullptr) return nullptr; // 比根节点值小, 递归左子树 if(key < root->val){ root->left = deleteNode(root->left, key); return root; } // 比根节点值大, 递归右子树 if(key > root->val){ root->right = deleteNode(root->right, key); return root; } // 删除结点 if(key == root->val){ // 如果没有左右孩子 if(!root->left && !root->right){ return nullptr; } // 只有左孩子, 没有右孩子 if (!root->right) { return root->left; } // 只有右孩子, 没有左孩子 if (!root->left) { return root->right; } else{ // 左右孩子都有, 找到比root大的最小结点successor(在右子树的最左边) TreeNode *successor = root->right; while (successor->left) { successor = successor->left; } // 在root的右子树中删除successor root->right = deleteNode(root->right, successor->val); // 用successor来代替root的位置 successor->right = root->right; successor->left = root->left; return successor; } } return root; } };
复杂度分析
-
时间复杂度:O(n),n为节点总数,最坏情况下,找successor和删除它都需要便利整个树 空间复杂度:O(n),n为节点总数,递归的最大深度就是n
上一篇:
IDEA上Java项目控制台中文乱码