剑指Offer_62_二叉搜索树的第k个结点

题目描述

给定一颗二叉搜索树,请找出其中的第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 {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        Result re = kThNode(pRoot, k, 0);
        return re.node;
    }

    private Result kThNode(TreeNode pRoot, int k, int cur) {
        if (pRoot == null) return new Result(null, cur);
        Result rl = kThNode(pRoot.left, k , cur);
        if (rl.k == k) return rl;
        cur = rl.k + 1;
        if (cur == k) return new Result(pRoot, k);
        Result rr =  kThNode(pRoot.right, k, cur);
        if (rr.k == k) return rr;
        return new Result(null,rr.k);
    }

    private class Result{
        TreeNode node;
        int k; //第几个数据

        public Result(TreeNode node, int k){
            this.node = node;
            this.k = k;
        }
    }
}
原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5828864.html