牛客网 二叉搜索树的第k个结点

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
           
           if(pRoot==NULL||k<=0)
               return NULL;
            vector<TreeNode*> p;
            trave(pRoot,p);
             if(k>p.size())
              return NULL;
          else
         return p[k-1];

         
    }
     void trave(TreeNode* pRoot,vector<TreeNode*> &p) //注意这里的参数,传入的是p的引用,不是p!不然保存不下来
         {
             if(pRoot==NULL)
                  return ;
           
             trave(pRoot->left,p);
             p.push_back(pRoot);
             trave(pRoot->right,p);
                return ;
         
     }
     int numbers(TreeNode* pRoot)
         {
          if(pRoot==NULL)
               return 0;
          else
              {
              int left=numbers(pRoot->left);
              int right=numbers(pRoot->right);
              return 1+left+right;}
     }
};

 

posted @ 2017-04-06 10:45  爱编程的小羊  阅读(283)  评论(0编辑  收藏  举报