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).
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; } };
相关文章推荐
- 450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- 450. Delete Node in a BST**
- [leetcode]450. Delete Node in a BST
- leetcode 450. Delete Node in a BST
- 450. Delete Node in BST
- 450. Delete Node in a BST
- leetcode-450.delete a node in a BST
- 450. Delete Node in a BST
- [LeetCode]450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- [hard]450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- LeetCode 450.Delete Node in a BST
- 【二叉搜索树:删除指定结点】leetcode 450. Delete Node in a BST
- 450. Delete Node in a BST
- Leetcode-450. Delete Node in a BST
- 450. Delete Node in a BST
- 450. Delete Node in a BST