Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions 18 October Median of BST
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution {
public:
int countNodes(Node* root) {
if (!root) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}

int findKth(Node* root, int& k) {
if (!root) return -1;
int left = findKth(root->left, k);
if (left != -1) return left;
k--;
if (k == 0) return root->data;
return findKth(root->right, k);
}

int findMedian(Node* root) {
int total = countNodes(root);
int k = (total + 1) / 2;
return findKth(root, k);
}
};