|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <string> |
| 4 | +#include <algorithm> |
| 5 | +#include <cstdio> |
| 6 | +using namespace std; |
| 7 | +struct TreeNode { |
| 8 | + int val; |
| 9 | + TreeNode *left; |
| 10 | + TreeNode *right; |
| 11 | + TreeNode(int x) : val(x), left(nullptr), right(nullptr){} |
| 12 | +}; |
| 13 | +class Solution { |
| 14 | +public: |
| 15 | + int kthSmallest(TreeNode *root, int k) { |
| 16 | + int result; |
| 17 | + /* |
| 18 | + if (root == nullptr) { |
| 19 | + return 0; |
| 20 | + } |
| 21 | + */ |
| 22 | + kthSmallest(root, k, result); |
| 23 | + return result; |
| 24 | + } |
| 25 | +private: |
| 26 | + bool kthSmallest(TreeNode *root, int &k, int &result) { |
| 27 | + if (root->left) { |
| 28 | + if (kthSmallest(root->left, k, result)) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + } |
| 32 | + k -= 1; |
| 33 | + if (k == 0) { |
| 34 | + result = root->val; |
| 35 | + return true; |
| 36 | + } |
| 37 | + if (root->right) { |
| 38 | + if (kthSmallest(root->right, k, result)) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + } |
| 42 | + return false; |
| 43 | + } |
| 44 | +}; |
| 45 | +TreeNode *mk_node(int val) |
| 46 | +{ |
| 47 | + return new TreeNode(val); |
| 48 | +} |
| 49 | +TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right) |
| 50 | +{ |
| 51 | + root->left = left; |
| 52 | + root->right = right; |
| 53 | + return root; |
| 54 | +} |
| 55 | +TreeNode *mk_child(TreeNode *root, int left, int right) |
| 56 | +{ |
| 57 | + return mk_child(root, new TreeNode(left), new TreeNode(right)); |
| 58 | +} |
| 59 | +TreeNode *mk_child(int root, int left, int right) |
| 60 | +{ |
| 61 | + return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right)); |
| 62 | +} |
| 63 | +int main(int argc, char **argv) |
| 64 | +{ |
| 65 | + Solution solution; |
| 66 | + TreeNode *root = mk_child(6, 4, 8); |
| 67 | + mk_child(root->left, 3, 5); |
| 68 | + mk_child(root->right, 7, 9); |
| 69 | + for (int i = 1; i <= 7; ++i) |
| 70 | + printf("%d\n", solution.kthSmallest(root, i)); |
| 71 | + return 0; |
| 72 | +} |
0 commit comments