题目
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;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24