首页 > 其他 > 详细

二叉搜索树的第k个结点

时间:2016-09-03 17:53:47      阅读:179      评论:0      收藏:0      [点我收藏+]

给定一颗二叉搜索树,请找出其中的第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 cnt = 0;
    TreeNode cnode = null;
    TreeNode KthNode(TreeNode pRoot, int k) {
        if (pRoot == null || k == 0)
            return null;
          
        pre(pRoot, k);
        return cnode;
    }
    
    void pre(TreeNode node, int k) {
        if (node == null)
            return ;
        
        pre(node.left, k);
        cnt ++;
        if (cnt == k) {
            cnode = node;
            return ;
        }
        pre(node.right, k);
        return ;
    }
}

 

二叉搜索树的第k个结点

原文:http://www.cnblogs.com/wxisme/p/5837507.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!