1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 TreeNode* deleteNode(TreeNode* root, int key) 14 { 15 if(!root) return NULL;//如果root为空,直接返回NULL 16 17 if(root->val > key) root->left = deleteNode(root->left,key);//如果当前节点的值大于key,在左子树里面找 18 else if(root->val < key) root->right = deleteNode(root->right,key);//如果当前节点的值小于key,在右子树里面找 19 else//当前节点的值等于key 20 { 21 if(root->right == NULL) //如果没有右子树 22 { 23 TreeNode* left = root->left;//备份该节点的左子树 24 delete root;//删除该节点 25 return left;//返回该节点的左子树 26 } 27 else //如果有右子树 28 { 29 TreeNode* right = root->right;//备份该节点的右子树 30 while(right->left) right = right->left;//找到右子树最左的节点 31 swap(root->val,right->val);//交换该节点与右子树最左节点的值 32 root->right = deleteNode(root->right,key);//在该节点的右子树进行删除 33 } 34 } 35 return root; 36 } 37 };
原文地址:https://www.cnblogs.com/yuhong1103/p/12617868.html
时间: 2024-10-30 07:15:56