文章目录
- 题目
- 代码(10.2 首刷看解析)
题目
Leetcode 450. 删除二叉搜索树中的节点
代码(10.2 首刷看解析)
class Solution {
public:TreeNode* deleteNode(TreeNode* root, int key) {if(!root)return root;if(root->val < key) {root->right = deleteNode(root->right, key);} else if(root->val > key) {root->left = deleteNode(root->left, key);} else {if(!root->left) return root->right;if(!root->right) return root->left;// 两边都有TreeNode* minNode = root->right; // 获取右子树最小的节点while(minNode->left)minNode = minNode->left;root->right = deleteNode(root->right, minNode->val);minNode->left = root->left;minNode->right = root->right;root = minNode;}return root;}
};