From 829c80cdb06450dab02dac924aa3e46a539d3301 Mon Sep 17 00:00:00 2001 From: Aditi Aggarwal Date: Tue, 16 Oct 2018 20:32:16 +0530 Subject: [PATCH] Added code for delete operation on BST (#19516) --- .../algorithms/binary-search-trees/index.md | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/client/src/pages/guide/english/algorithms/binary-search-trees/index.md b/client/src/pages/guide/english/algorithms/binary-search-trees/index.md index 9735a8b045..0a33c0d091 100644 --- a/client/src/pages/guide/english/algorithms/binary-search-trees/index.md +++ b/client/src/pages/guide/english/algorithms/binary-search-trees/index.md @@ -154,6 +154,42 @@ void insert(int data) { } } ``` +#### Delete Operation +void deleteNode(struct node* root, int data){ + + if (root == NULL) root=tempnode; + + if (data < root->key) + root->left = deleteNode(root->left, key); + + + else if (key > root->key) + root->right = deleteNode(root->right, key); + + else + { + if (root->left == NULL) + { + struct node *temp = root->right; + free(root); + return temp; + } + else if (root->right == NULL) + { + struct node *temp = root->left; + free(root); + return temp; + } + + struct node* temp = minValueNode(root->right); + + root->key = temp->key; + + root->right = deleteNode(root->right, temp->key); + } + return root; + +} Binary search trees (BSTs) also give us quick access to predecessors and successors. Predecessors can be described as the node that would come right before the node you are currently at. @@ -244,4 +280,4 @@ Complete Binary Tree: A Binary Tree is complete Binary Tree if all levels are co / \ / \ 40 50 100 40 / \ / - 8 7 9 \ No newline at end of file + 8 7 9