230 Kth Smallest Element in a BST 二叉搜索树中第K小的元素

给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第k个最小的元素。

注意:
你可以假设k总是有效的,1≤ k ≤二叉搜索树元素个数。

进阶:
如果经常修改二叉搜索树(插入/删除操作)并且你需要频繁地找到第k小值呢? 你将如何优化kthSmallest函数?

详见:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

Java实现:

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

 C++实现:

方法一:递归实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        return helper(root,k);
    }
    int helper(TreeNode* root,int &k)
    {
        if(!root)
        {
            return -1;
        }
        int val=helper(root->left,k);
        if(k==0)
        {
            return val;
        }
        if(--k==0)
        {
            return root->val;
        }
        return helper(root->right,k);
    }
};

方法二:非递归实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        if(root==nullptr)
        {
            return -1;
        }
        stack<TreeNode*> stk;
        while(root||!stk.empty())
        {
            if(root)
            {
                stk.push(root);
                root=root->left;
            }
            else
            {
                root=stk.top();
                stk.pop();
                if(k==1)
                {
                    return root->val;
                }
                --k;
                root=root->right;
            }
        }
        return -1;
    }
};

  

原文地址:https://www.cnblogs.com/xidian2014/p/8758929.html