题目描述

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

 

题目链接:

https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

 

 

分析:

中序遍历。

 

 

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

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

    }

}
*/
public class Solution {
    private TreeNode node =null;
    private int pos = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(null == pRoot){
            return null;
        }
        //左子树
        KthNode(pRoot.left,k);
        //当前节点
        pos++;
        if(pos == k && node == null){
            node = pRoot;
            return node;
        }
        //右子树
        KthNode(pRoot.right,k);
        return node;
    }
    

}

 

posted on 2020-06-13 23:28  MoonBeautiful  阅读(153)  评论(0编辑  收藏  举报