Iven a root of Binary Search Tree with unique value forEach node. Remove the node with given value. If There is no such a node with given value in the binary search tree, DoNothing . You should keep the tree still a binary search tree after removal. has you met ThisQuestion in a real interview?yesexamplegiven binary search tree:5/ 3 6/ 2 4Remove3, you can eitherreturn: 5/ 2 6 4or:5/ 4 6/2
Analysis: Assuming that the current node is root
1. If value < Root.val, the node to be deleted in the left subtree, toward the left subtree recursively, and the return value after the end of the operation as the new Root.left
2. If value > Root.val, the node to be deleted in the right subtree, toward the right subtree recursively
3. If root = = NULL, recursion to a null point indicating that the value to be deleted does not exist, return null, and that the corresponding subtree of the null point's parent is null and has no effect on the structure of the tree
4. If value = = Root.val, it means that root is deleted.
A. If root.left = = NULL, return root.right
B. If root.right = = null, return Root.left (these two cases actually contain three situations in which only one child and one child are not)
C. If two children are present, find the smallest node from the right subtree, swap with root, and then recursively call the function to delete the Root.val in the right sub-tree
1 /**2 * Definition of TreeNode:3 * public class TreeNode {4 * public int val;5 * Public TreeNode left and right;6 * Public TreeNode (int val) {7 * This.val = val;8 * This.left = This.right = null;9 * }Ten * } One */ A Public classSolution { - /** - * @paramroot:the root of the binary search tree. the * @paramvalue:remove the node with given value. - * @return: The root of the binary search tree after removal. - */ - PublicTreeNode RemoveNode (TreeNode root,intvalue) { + //Write your code here - if(Root = =NULL)return NULL; + if(Value <root.val) ARoot.left =RemoveNode (root.left, value); at Else if(Value >root.val) -Root.right =RemoveNode (root.right, value); - Else { - if(Root.left = =NULL)returnRoot.right; - if(Root.right = =NULL)returnRoot.left; -TreeNode minofright =findmin (root.right); in //swap root and Minofright - inttemp =Root.val; toRoot.val =Minofright.val; +Minofright.val =temp; -Root.right =RemoveNode (Root.right, minofright.val); the } * returnRoot; $ }Panax Notoginseng - PublicTreeNode findmin (TreeNode cur) { the while(Cur.left! =NULL) { +Cur =Cur.left; A } the returncur; + } -}
Lintcode:remove Node in Binary Search Tree