首页 > 其他 > 详细

Kth Smallest Element in a BST

时间:2015-07-15 18:31:16      阅读:252      评论:0      收藏:0      [点我收藏+]

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST‘s total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private int n = 0;
    private TreeNode re_node;
    
    //中序遍历二叉排序树
    public void InOrderTravel(TreeNode root,int k) {
        if(root!=null) {
            InOrderTravel(root.left,k);
            n++;
            if(n==k) {
                this.re_node = root;
                return;
            }
            InOrderTravel(root.right,k);
        }
    }
    
    
    public int kthSmallest(TreeNode root, int k) {
        InOrderTravel(root,k);
        return this.re_node.val;
    }
}

 

Kth Smallest Element in a BST

原文:http://www.cnblogs.com/mrpod2g/p/4648766.html

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