From 3d97a9d590786e401849af5f4e2b2c21d70d73f1 Mon Sep 17 00:00:00 2001 From: Akshay Soni <109035961+akshaysoni10@users.noreply.github.com> Date: Wed, 19 Oct 2022 12:04:46 +0530 Subject: [PATCH] Add files via upload --- Kth_Smallest_Element_in_BST.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Kth_Smallest_Element_in_BST.cpp diff --git a/Kth_Smallest_Element_in_BST.cpp b/Kth_Smallest_Element_in_BST.cpp new file mode 100644 index 0000000..04b72e2 --- /dev/null +++ b/Kth_Smallest_Element_in_BST.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int solve(TreeNode* root, int &i, int k){ + //base case + if(root == NULL){ + return -1; + } + + int left = solve(root -> left, i, k); + if(left != -1){ + return left; + } + + i++; + if(i == k){ + return root -> val; + } + return solve(root -> right, i, k); + } + + int kthSmallest(TreeNode* root, int k) { + int i = 0; + int ans = solve(root, i, k); + return ans; + } +}; \ No newline at end of file