1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (root == nullptr) return root; if (root->val == key) { if (root->left == nullptr && root->right == nullptr) { delete root; return nullptr; } else if (root->left == nullptr) { auto retNode = root->right; delete root; return retNode; } else if (root->right == nullptr) { auto retNode = root->left; delete root; return retNode; } else { TreeNode* cur = root->right; while(cur->left != nullptr) { cur = cur->left; } cur->left = root->left; TreeNode* tmp = root; root = root->right; delete tmp; return root; } } if (root->val > key) root->left = deleteNode(root->left, key); if (root->val < key) root->right = deleteNode(root->right, key); return root; } };
|