Created
May 29, 2019 18:28
-
-
Save madhur/4bc201db1d388f965654ca76c4c9dd9a to your computer and use it in GitHub Desktop.
Delete node from bst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public TreeNode delete(TreeNode root, int data) { | |
if(root == null) { | |
return null; | |
} else if(data < root.data) { | |
root.left = delete(root.left, data); | |
} else if(data > root.data) { | |
root.right = delete(root.right, data); | |
} else { //element found | |
if(root.left != null && root.right != null) { //full node case | |
root.data = findMin(root.right).data; | |
root.right = delete(root.right, root.data); | |
} else if(root.left == null && root.right == null) { | |
root = null; | |
} | |
else if(root.left == null) { | |
root = root.right; | |
} else if(root.right == null) { | |
root = root.left; | |
} | |
} | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment