【两次过】Lintcode 902. Kth Smallest Element in a BST

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

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

样例

Given root = {1,#,2}, k = 2, return 2.

挑战

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?

注意事项

You may assume k is always valid, 1 ≤ k ≤ BST's total elements.


解题思路1:

中序遍历即可。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
     int res = 0;
     int kk = 0;
    public int kthSmallest(TreeNode root, int k) {
        // write your code here
        kk = k;
        
        kthSmallest(root);
        
        return res;
    }
    
    private void kthSmallest(TreeNode root){
        if(root == null)
            return;
            
        kthSmallest(root.left);
        
        if(--kk == 0)
            res = root.val;
        
        kthSmallest(root.right);
    }
}

解题思路2:

中序遍历的非递归版本。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
    public int kthSmallest(TreeNode root, int k) {
        // write your code here
        Stack<TreeNode> stack = new Stack<>();
        
        while(root!=null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();
            
            if(--k == 0)
                return root.val;
            
            root = root.right;
        }
        
        return 0;
    }

}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82992660