From 36eeb532b88ec3333fa8502f54ef601120559352 Mon Sep 17 00:00:00 2001 From: Shobha <88886122+Shobha-27@users.noreply.github.com> Date: Fri, 7 Oct 2022 20:17:39 +0530 Subject: [PATCH] Create Height (Maximum Depth) of a Binary Search Tree.cpp --- ...Maximum Depth) of a Binary Search Tree.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 C++/Height (Maximum Depth) of a Binary Search Tree.cpp diff --git a/C++/Height (Maximum Depth) of a Binary Search Tree.cpp b/C++/Height (Maximum Depth) of a Binary Search Tree.cpp new file mode 100644 index 0000000..7b95b0c --- /dev/null +++ b/C++/Height (Maximum Depth) of a Binary Search Tree.cpp @@ -0,0 +1,65 @@ + #include + + using namespace std; + + struct node { + int data; + node * left; + node * right; + }; + + struct node * getNode(int data) { + node * newNode = new node(); + newNode -> data = data; + newNode -> left = NULL; + newNode -> right = NULL; + return newNode; + } + + void inorder(struct node * root) { + if (root != NULL) { + inorder(root -> left); + cout << root -> data << " "; + inorder(root -> right); + } + } + + struct node * Insert(struct node * root, int data) { + if (root == NULL) + return getNode(data); + + if (data < root -> data) + root -> left = Insert(root -> left, data); + else if (data > root -> data) + root -> right = Insert(root -> right, data); + + return root; + } + + int FindHeight(node * root) { + if (root == NULL) + return 0; + + else { + int lb = FindHeight(root -> left); + int rb = FindHeight(root -> right); + return max(lb, rb) + 1; + } + } + int main() { + node * root = NULL; + root = Insert(root, 7); + Insert(root, 9); + Insert(root, 4); + Insert(root, 1); + Insert(root, 5); + + cout << "Inorder: "; + inorder(root); + cout << endl; + + cout << "Height of the tree is " << FindHeight(root) << endl; + cout << "Max. Depth of the tree is " << FindHeight(root) - 1; + + return 0; + }