-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.cpp
More file actions
35 lines (33 loc) · 721 Bytes
/
program.cpp
File metadata and controls
35 lines (33 loc) · 721 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "../include/pre.h"
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
*};
*/
int currentMinth;
bool gotKth;
int kthMin;
void helper(TreeNode* root, int k)
{
if (!root) return;
if (!gotKth) helper(root->left, k)
currentMinth++;
if (currentMinth == k) {
kthMin = root->val;
gotKth = true;
}
if (!gotKth) helper(root->right, k);
}
int kthSmallest(TreeNode* root, int k)
{
currentMinth = 0;
gotKth = false;
kthMin = 0;
helper(root, k);
if (gotKth) return kthMin;
else throw(std::exception("Not in this tree"));
}