您的位置:首页 > Web前端 > Node.js

450. Delete Node in a BST

2017-09-07 11:00 531 查看
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:

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

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

/**
* 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:
bool isLeafNode(struct TreeNode * root){
if(root == NULL){
return true;
}
if(!(root->left) && !(root->right)){
return true;
}else{
return false;
}
}

TreeNode * deleteRoot(struct TreeNode * root) {
struct TreeNode * newNode = root;
struct TreeNode * father = root;
int len;

if(root == NULL ||isLeafNode(root)){
return NULL;
}

/*find the max node of the left Tree*/
if(root->left){
newNode = root->left;
while(newNode->right){
if(newNode->right){
father = newNode;
}
newNode = newNode->right;
}
}

/*find the min node of the right Tree*/
if(root->left == NULL && root->right){
newNode = root->right;
while(newNode->left){
if(newNode->left){
father = newNode;
}
newNode = newNode->left;
}
}

//printf("swap key = %d\n\r",newNode->val);
root->val = newNode->val;//change the root value
if(father->left == newNode){
father->left = deleteRoot(newNode);
}
if(father->right == newNode){
father->right = deleteRoot(newNode);
}

return root;
}

TreeNode* deleteNode(TreeNode* root, int key) {
struct TreeNode * newNode = NULL;

if(root == NULL){
return NULL;
}

if(root->val == key){
//printf("delete root->val = %d\n\r",root->val);
return deleteRoot(root);
}

if(key > root->val){
root->right = deleteNode(root->right,key);
}
if(key < root->val){
root->left = deleteNode(root->left,key);
}

return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: