-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkthSmallestInBinaryTree.h
56 lines (47 loc) · 1.25 KB
/
kthSmallestInBinaryTree.h
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
//
// Created by so_go on 2019/6/5.
//
#ifndef SRC_KTHSMALLESTINBINARYTREE_H
#define SRC_KTHSMALLESTINBINARYTREE_H
//Definition for a binary tree node.
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class KthSmalledstInBinaryTree {
public:
// 二叉搜索树中序遍历
// dfs: 递归搜索第k小的元素
//
bool isfind = false;
int kthSmallest(TreeNode* root, int k) {
vector<int> numbers;
dfs(numbers, root, k);
// cout << "number of vector: " << numbers.size() << endl;
return numbers.back();
}
void dfs(vector<int>& values, TreeNode *node, int k){
// 递归
if(not isfind){
if(node->left ){
dfs(values, node->left, k);
}
if(not isfind){
cout << node->val << endl;
values.push_back(node->val);
if(values.size() == k){
isfind = true;
}
}
if(node->right and not isfind){
dfs(values, node->right, k);
}
}
}
};
#endif //SRC_KTHSMALLESTINBINARYTREE_H