leetcode腾讯精选230

题目:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/submissions/
代码:
/**

  • 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) {
    TreeNode *pcur = root;
    if(root ==NULL)
    return -1;
    vector array;
    stack s;
    while(!s.empty()||root)
    {
    while(pcur)
    {
    s.push(pcur);
    pcur = pcur->left;
    }

          if(s.empty())
         {
             break;
         }
     	pcur = s.top();
     	array.push_back(pcur->val);
     	s.pop();
         
        
     	pcur = pcur->right;
    

    }
    return array[k - 1];
    }

};

你可能感兴趣的:(c++)