二叉搜索树
建树
删除节点,三种情况,递归处理。左右子树都存在,两种方法,一种找到左子树最大节点,赋值后递归删除。找右子树最小同理
1 class Solution { 2 public: 3 TreeNode* deleteNode(TreeNode* root, int key) { 4 if(root==NULL)return NULL; 5 if(root->val>key) 6 { 7 root->left = deleteNode(root->left,key); 8 return root; 9 } 10 if(root->val<key) 11 { 12 root->right = deleteNode(root->right,key); 13 return root; 14 } 15 if(root->left==NULL&&root->right==NULL)return NULL; 16 if(root->left==NULL&&root->right!=NULL)return root->right; 17 if(root->left!=NULL&&root->right==NULL)return root->left; 18 int val = findMax(root->left); 19 root->val=val; 20 root->left = deleteNode(root->left,val); 21 return root; 22 } 23 int findMax(TreeNode* root) 24 { 25 if(root->right==NULL)return root->val; 26 return findMax(root->right); 27 } 28 };