[InterviewBit] Kth Smallest Element In Tree

Kth Smallest Element In Tree

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* A, vector<int>& now) {
if(A == NULL) return;
now.push_back(A->val);
dfs(A->left, now);
dfs(A->right, now);
}
int Solution::kthsmallest(TreeNode* A, int B) {
vector<int> now;
dfs(A,now);
sort(begin(now),end(now));
return now[B-1];
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/13/PS/interviewbit/kth-smallest-element-in-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.