码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Kth Smallest Element in a BST

时间:2018-05-21 14:38:58      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:rsa   optimize   operation   insert   while   function   inpu   func   就会   

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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
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?

那么这道题给的提示是让我们用BST的性质来解题,最重要的性质是就是左<根<右,那么如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //inorder traversal
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        int result = 0;
        
        while(!stack.isEmpty() || p != null){
            if(p != null){
                stack.push(p);
                p = p.left;
            }
            else{
                TreeNode t = stack.pop();
                k--;
                if(k == 0){
                    result = t.val;
                }
                p = t.right;
            }
        }
        return result;
        
    }
}

 

LeetCode - Kth Smallest Element in a BST

标签:rsa   optimize   operation   insert   while   function   inpu   func   就会   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9066568.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!