55.剑指Offer-二叉查找树的第 K 个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/88978663

题目描述

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

解题思路

利用二叉查找树中序遍历有序的特点。

private TreeNode ret;
private int cnt = 0;

public TreeNode KthNode(TreeNode pRoot, int k) {
    inOrder(pRoot, k);
    return ret;
}

private void inOrder(TreeNode root, int k) {
    if (root == null || cnt >= k)
        return;
    inOrder(root.left, k);
    cnt++;
    if (cnt == k)
        ret = root;
    inOrder(root.right, k);
}

也可以cnt=k,cnt--,if(cnt==0){ret=root}。以上代码中主要是利用了中序遍历,因为二叉搜索树很符合中序遍历的特点。

猜你喜欢

转载自blog.csdn.net/cuicanxingchen123456/article/details/88978663
今日推荐