-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth_smallest_element.cpp
More file actions
84 lines (77 loc) · 2.27 KB
/
kth_smallest_element.cpp
File metadata and controls
84 lines (77 loc) · 2.27 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* =====================================================================================
*
* Filename: kth_smallest_element.cpp
*
* Description: 230. Kth Smallest Element in a BST.
* https://leetcode.com/problems/kth-smallest-element-in-a-bst/
*
* Version: 1.0
* Created: 02/26/23 10:58:27
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stack>
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
static TreeNode *convert(const std::vector<int *> &nums, const int i = 0) {
if (i >= nums.size() || nums[i] == nullptr) {
return nullptr;
}
TreeNode *root = new TreeNode(*nums[i]);
root->left = convert(nums, 2 * i + 1);
root->right = convert(nums, 2 * i + 2);
return root;
}
};
// Inorder traversal by breadth first search
class Solution {
public:
int kthSmallest(TreeNode *root, int k) {
std::stack<TreeNode *> nodes;
while (root != nullptr || !nodes.empty()) {
while (root != nullptr) {
nodes.push(root);
root = root->left;
}
root = nodes.top();
if (--k == 0) {
return root->val;
}
nodes.pop();
root = root->right;
}
return -1;
}
};
TEST(Solution, kthSmallest) {
#define _N(x) new int(x)
std::vector<std::tuple<TreeNode *, int, int>> cases = {
std::make_tuple(TreeNode::convert(std::vector<int *>{_N(3), _N(1), _N(4),
nullptr, _N(2)}),
1, 1),
std::make_tuple(
TreeNode::convert(std::vector<int *>{_N(5), _N(3), _N(6), _N(2),
_N(4), nullptr, nullptr, _N(1)}),
3, 3),
};
for (auto &c : cases) {
EXPECT_EQ(Solution().kthSmallest(std::get<0>(c), std::get<1>(c)),
std::get<2>(c));
}
#undef _N
}