902. Kth Smallest Element in a BST

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

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

样例
Given root = {1,2}, k = 2, return 2.

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

class Solution {
public:
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */

    //迭代遍历到最后(思考如何提前终止)
    int count = 0;
    int res;
    int kthSmallest(TreeNode * root, int k) {
        // write your code here
        if (root->left != NULL) kthSmallest(root->left, k);
        if (++count == k) res = root->val;     //①
        if (root->right != NULL) kthSmallest(root->right, k);
        return res;
    }


    
    //循环
    int kthSmallest(TreeNode * root, int k) {
        // write your code here
        std::stack<TreeNode*> sta;
        while (true) {
            while (root) {
                sta.push(root);
                root = root->left;
            }
            if (sta.empty()) break;
            root = sta.top();
            sta.pop();
            if(--k==0) return root->val;
            root = root->right;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/narjaja/p/10004277.html
今日推荐