Kth Smallest Element in a BST

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

    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.

  2. 解答
    class Solution1 {
    public:
         
        int kthSmallest(TreeNode* root, int k) {
            inorderTraversal(root); 
             return res[k-1];
        }
        
      void inorderTraversal(TreeNode* root) 
        {
            if(root)
            {
                
                inorderTraversal(root->left);
                res.push_back(root->val);
                inorderTraversal(root->right);
            }
         //   return res;
        }
        
    private:
         vector<int> res;
    };
    
    class Solution2 {
    public:
         
        int kthSmallest(TreeNode* root, int k) 
        {
             vector<int> res;
             int sum=0;
             vector<TreeNode *> f1;
             
             while(root)
             {
                 f1.push_back(root);
                 root=root->left;
             }
             TreeNode *temp;
             while(!f1.empty() )
             {
                temp=f1.back();
                 
                 
                res.push_back(temp->val);
                sum++;
                if(sum==k) return temp->val;
                f1.pop_back();
                     
                  
                 if(temp->right!=NULL)
                 {
                     TreeNode *f=temp->right;
                     while(f)
                     {
                           f1.push_back(f);
                           f=f->left;
                     }
                 }
               
             }
        }
    };
    
    class Solution {
    public:
         
        int kthSmallest(TreeNode* root, int k) 
        {
            int sum=0;
            stack<TreeNode *> f1;
            // inorder
            while(root || !f1.empty())
            {
                while(root)
                {
                    f1.push(root);
                    root=root->left;
                }
                if(!f1.empty())
                {
                    TreeNode *temp;
                    temp=f1.top();
                    sum++;
                    if(sum==k) return temp->val;
                    f1.pop();
                    
                    if(temp->right!=NULL)
                    {
                        root=temp->right;
                    }
                }
                
                
            }
        }
        
    };


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页