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 tree‘s property should be maintained. Assumptions There are no duplicate keys in the binary search tree
//==== this code is not right. needs to be updated
1 public class Solution { 2 public TreeNode delete(TreeNode root, int key) { 3 // Write your solution here. 4 if (root == null) { 5 return null ; 6 } 7 //if found, then set the root to null(means the following leafs will be removed ) 8 if (root.key == key) { 9 return null; 10 } 11 if (root.key < key) { 12 //go to the right 13 root.right = delete(root.right, key); 14 } 15 if (root.key > key) { 16 root.left = delete(root.left, key) ; 17 } 18 return root; 19 } 20 }
原文地址:https://www.cnblogs.com/davidnyc/p/8655271.html
时间: 2024-10-09 08:28:31