二叉搜索树第k个节点(中序遍历保留每层count)

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
1.最容易想到的情况,中序遍历保存在vector里,复杂度为o(n)
/*
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 result;
     mid( pRoot,result);
     if(k>result.size())
         return NULL;
     return result[k-1];
        
    }
    void mid(TreeNode* pRoot,vector&result)
    {
        if(pRoot==NULL)
            return ;
         if(pRoot->left)
           mid(pRoot->left,result);
         result.push_back(pRoot);
          if(pRoot->right)
           mid(pRoot->right,result);
    }
    
};

注意边界条件!   k<=0或者超过n,给定根节点为空的情况。

2.

/*
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;
    
     return  mid( pRoot,k);
        
    }
   TreeNode* mid(TreeNode* pRoot,int&k)
    {  TreeNode*target=NULL;
        if(pRoot==NULL)
            return NULL;
         target=mid(pRoot->left,k);
         if(target)
             return target;
         if(--k==0)
              return pRoot;
           target= mid(pRoot->right,k);
         if(target!=NULL)
             return target;
     return NULL;
      
    }
    
};




你可能感兴趣的:(小R天天写程序)