剑指 Offer 54. 二叉搜索树的第k大节点

这里要注意题目的说法,课本、牛客 都是第K个节点  ,LeetCode 上说的是第K大的节点。大家都知道 二叉搜索树的中序遍历

可以得到一个递增序列,那么 第K个, 和第K大 是稍稍不一样的。

LeetCode

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int k;
    int target;
    public int kthLargest(TreeNode root, int k) {
            this.k = k ;
            dfs(root);
            return target;
    }
    
    void dfs(TreeNode root){
        if(root == null) return;
        dfs(root.right);
        if(k == 0) return;
        if(--k == 0)
        target = root.val;
        dfs(root.left);
    }
}

牛客

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode res;
    int count = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null || k <= 0){
            return null;
        }
        dfs(pRoot,k);
        return res;
    }
    void dfs(TreeNode root, int k){
        if(count < k && root.left != null){
            dfs(root.left,k);
        }
        
        if(++count == k){
            res = root;
            return;
        }
        if(count < k && root.right != null){
            dfs(root.right,k);
        }
    }

}