450. Delete Node in a BST

来源:互联网 发布:淘宝上最好吃的美食 编辑:程序博客网 时间:2024/06/06 18:49

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

递归的思想,如果当前节点的值>target就在左子树里递归,<target就在右子树里递归。

如果要删除当前节点的话又分两种情况:

1、当前节点左子树或右子树为空:直接将不为空的一边赋给当前节点就好。

2、找到当前右子树的最小值赋给当前节点,递归删除右子树中的最小值节点。

/** * 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) return NULL;                if(root->val>key) root->left=deleteNode(root->left, key);        else if(root->val<key) root->right=deleteNode(root->right, key);        else{            if(!root->left||!root->right) root=!(root->left)?root->right:root->left;            else{                auto rightMin=root->right;                while(rightMin->left) rightMin=rightMin->left;                root->val=rightMin->val;                root->right=deleteNode(root->right, rightMin->val);            }        }        return root;    }};


0 0