63. 二叉搜索树的第k个结点《剑指Offer》(Java版)

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

 

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

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

    }

}
*/
public class Solution {
    int i = 0;

    TreeNode KthNode(TreeNode pRoot, int k) {
        if (pRoot == null) {
            return null;
        }
        //中序遍历次序与大小次序相同
        TreeNode res = KthNode(pRoot.left, k);
        if (res != null) {
            return res;
        }
        i++;
        if (k == i) {
            return pRoot;
        }
        res = KthNode(pRoot.right, k);
        return res;
    }


}

 

你可能感兴趣的:(63. 二叉搜索树的第k个结点《剑指Offer》(Java版))