45.二叉搜索樹第K大的節點
給定一棵二叉搜索樹,請找出其中第k大的節點。
示例 1:
輸入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
輸出: 4
示例 2:
輸入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
輸出: 4
思路
二叉搜索樹中序遍歷的結果是一個從小帶大的序列。由於是求第K大,所以我們需要一種從大到小的序列,第K個元素就是第K大。
那就很簡單了,先中序遍歷保存至一個棧中,然後出棧即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
LinkedList<Integer> stack=new LinkedList<>();
public int kthLargest(TreeNode root, int k) {
getTreeByinorder(root,stack);
int res=0;
while(--k>0)
{
stack.pop();
}
return stack.peek();
}
public void getTreeByinorder (TreeNode root,LinkedList<Integer> stack)
{
if(root==null)
{
return;
}
getTreeByinorder(root.left,stack);
stack.push(root.val);
getTreeByinorder(root.right,stack);
}
}