Delete node in BST

来源:互联网 发布:python url encode 编辑:程序博客网 时间:2024/06/05 17:38

Question: delete the given value in BST.

This question is pretty tricky, to delete a node in BST, there are several cases to consider.

1: The node is one of the leaves, 2: the node only has right children, 3: the node only has left children, 4: the node has left and right children.









code:

TreeNode* deleteTreeNode(TreeNode* root, int val) {  if(!root) return NULL;  else {    if(val < root->val) root->left = deleteTreeNode(root->left, val);    else if(val > root->val) root->right = deleteTreeNode(root->right, val);    else {      // if there is no left child, no right child      if(root->left == NULL && root->right == NULL) {        delete root;        root = NULL;        return root;      }      else if(root->left == NULL) { // if there is no left subtree        TreeNode* tmp = root;        root = root->right;        delete tmp;        return root;      } else if(root->right == NULL) { // if there is no right subtree        TreeNode* tmp = root;        root = root->right;        delete tmp;        return root;      } else { // two children        struct TreeNode* tmp = findMin(root->right);        root->data = tmp->data;        root->right = deleteTreeNode(root->right, tmp->data);        return root;      }    }  }}
0 0