牛客网 剑指offer 二叉搜索树的第K个结点

时间限制:1秒空间限制:32768K热度指数:4328

**算法知识视频讲解

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

题解:二叉搜索树的中序遍历是递增的,所以可以用vector保存,然后遍历vector,返回第k个,如果没有返回NULL

代码如下:

/*
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)
    {
        vector<TreeNode*>v;
        print(pRoot,v);
        for(int i=0;i<v.size();++i){
            if(i+1==k){
                return v[i];
            }else if(i>=k)break;
        }
        return NULL;
    }
	void print(TreeNode* pRoot, vector<TreeNode*> &y){
        if(pRoot==NULL)return;
        print(pRoot->left,y);
        y.push_back(pRoot);
        print(pRoot->right,y);
    }
    
};

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦