Sponsored
Sponsored
This approach involves traversing the tree recursively to find the node to be deleted. Once found, we handle it based on different cases: the node has no children, one child, or two children. For the two children case, replace the node with its inorder successor (minimum of the right subtree).
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(h) due to recursion stack space.
1public TreeNode DeleteNode(TreeNode root, int key) {
2 if (root == null) return null;
3 if (key < root.val) {
4 root.left = DeleteNode(root.left, key);
5 } else if (key > root.val) {
6 root.right = DeleteNode(root.right, key);
7 } else {
8 if (root.left == null) return root.right;
9 if (root.right == null) return root.left;
10 TreeNode minNode = GetMin(root.right);
11 root.val = minNode.val;
12 root.right = DeleteNode(root.right, minNode.val);
13 }
14 return root;
15}
16
17private TreeNode GetMin(TreeNode node) {
18 while (node.left != null) node = node.left;
19 return node;
20}
In C#, the deletion process in a BST is performed recursively, taking care of all possible scenarios regarding node children.
This method uses an iterative approach with a stack to traverse and manipulate the binary search tree. By applying the concept of replacing with the inorder successor, this method ensures the tree's properties remain intact after deletion.
Time Complexity: O(h), where h is tree height.
Space Complexity: O(1) since no additional data structures are used.
1public
This iterative Java approach uses a temporary dummy node to simplify tree manipulation. It offers efficient node deletion without extensive recursion.