[题目链接]

preview -> 题目难度:简单
给一个二叉搜索树, 找到这个树中第n大的数字

题解

找到二叉搜索树中排名第n大的数字, 其实直接可以逆中序遍历, 得到一个有序的链表, 然后直接使用LinkList.get()方法, 直接找到第n个元素即可

源码

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
class Solution {
LinkedList<TreeNode> path = new LinkedList<>();
public int findTargetNode(TreeNode root, int cnt) {

if (root == null) {
return -1;
}

dfs(root);

return path.get(cnt-1);



}

void dfs(TreeNode cur) {
if (cur == null) {
return ;

}

dfs(cur.right);
path.add(cur);
dfs(cur.left);
}
}