- Delete the target key K in the given binary search tree if the binary search tree contains K. Return the root of the binary search tree.
- Find your own way to delete the node from the binary search tree, after deletion the binary search trees property should be maintained.
- Assumptions
- There are no duplicate keys in the binary search tree
- //==== this code is not right. needs to be updated
- public class Solution {public TreeNode delete(TreeNode root, int key) {
- // Write your solution here.
- if (root == null) {
- return null ;
- }
- //if found, then set the root to null(means the following leafs will be removed )
- if (root.key == key) {
- return null;
- }
- if (root.key <key) {
- //go to the right
- root.right = delete(root.right, key);
- }
- if (root.key> key) {
- root.left = delete(root.left, key) ;
- }
- return root;
- }
- }
- LF.53.Delete In Binary Search Tree
来源: http://www.bubuko.com/infodetail-2539939.html