由于涉及到树的结构变化,用递归写比较简单,竟然一次跑通了
/**
* 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 == NULL)
return root;
// 找到了待删除节点
if (root->val == key) {
// 待删除节点没有子节点
if (root->left == NULL && root->right == NULL)
return NULL;
// 待删除节点只有一个子节点,直接返回这个子节点
if (root->left == NULL && root->right != NULL)
return root->right;
if (root->left != NULL && root->right == NULL)
return root->left;
// 待删除节点有两个子节点,将右节点挂载在左节点的最右下处,返回做节点
if (root->left != NULL && root->right != NULL) {
// 找到左节点最右下的节点
TreeNode* ori = root->left;
while (ori->right != NULL) {
ori = ori->right;
}
// 然后把右节点挂载在最右下节点的右侧
ori->right = root->right;
root = root->left;
return root;
}
}
// 未找到待删除节点
else if (root->val > key) {
root->left = deleteNode(root->left, key);
} else if (root->val < key) {
root->right = deleteNode(root->right, key);
}
return root;
}
};
标签:right,TreeNode,root,随想录,二叉,NULL,树中,节点,left
From: https://www.cnblogs.com/huigugu/p/18680454