二叉搜索树的第k个结点

题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

public class Solution {
    
    private TreeNode node = null;
    private int key = 0;
    TreeNode KthNode(TreeNode pRoot, int k) {
        
        if(pRoot == null)
            return null;
        if(k == 0)
            return null;
        key = k;
        preOrder(pRoot);
        return node;
    }
    private void preOrder(TreeNode root) {
        
        if(root == null)
            return ;
        preOrder(root.left);
        key --;
        if(key == 0) {
            
            node = root;
            return;
        }
        preOrder(root.right);
    }
}

你可能感兴趣的:(二叉搜索树的第k个结点)