给定一棵二叉搜索树,请找出其中第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
限制:
1 ≤ k ≤ 二叉搜索树元素个数
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int res,k; public int kthLargest(TreeNode root, int k) { //中序遍历逆序,若为求第k小时正序 this.k = k; midOrder(root); return res; } private void midOrder(TreeNode root){ if(root == null){ return ; } //右子树 midOrder(root.right); k--; if(k == 0){ res = root.val; return; } //左子树 midOrder(root.left); } }