delete-node-in-a-bst
Posted 笨鸟居士的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了delete-node-in-a-bst相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/delete-node-in-a-bst/
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (root == NULL) { return NULL; } TreeNode* cur = root; TreeNode* last = NULL; while (cur != NULL && cur->val != key) { if (cur->val > key) { last = cur; cur = cur->left; } else { last = cur; cur = cur->right; } } if (cur == NULL) { return root; } TreeNode* tlast = cur; TreeNode* tcur; if (cur->left != NULL) { tcur = cur->left; while (tcur->right != NULL) { tlast = tcur; tcur = tcur->right; } if (tcur == tlast->left) { tlast->left = tcur->left; } else { tlast->right = tcur->left; } cur->val = tcur->val; } else if (cur->right != NULL) { tcur = cur->right; while (tcur->left != NULL) { tlast = tcur; tcur = tcur->left; } if (tcur == tlast->left) { tlast->left = tcur->right; } else { tlast->right = tcur->right; } cur->val = tcur->val; } else { if (last == NULL) { // only root return NULL; } if (cur == last->left) { last->left = NULL; } else if (cur == last->right){ last->right = NULL; } else { // error } } return root; } };
以上是关于delete-node-in-a-bst的主要内容,如果未能解决你的问题,请参考以下文章
**Leetcode 450. Delete Node in a BST