题解 | #二叉搜索树的第k个节点#

二叉搜索树的第k个节点

https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param proot TreeNode类 
     * @param k int整型 
     * @return int整型
     */
    vector<int> out;
    int zhongxubianli(TreeNode* &root){
        if (!root) {
            return -1;
        }
        zhongxubianli(root->left);
        out.push_back(root->val);
        zhongxubianli(root->right);
        return 0;
    } 
    int KthNode(TreeNode* proot, int k) {
        // write code here
        if (!proot) {
            return -1;
        }
        
        zhongxubianli(proot);
        if (out.size()<k) {
            return -1;
        }
        if (k==0) {
            return -1;
        }

        return out[k-1];
    }
};

对于搜索二叉树,使用中序遍历即可按照从小到大的顺序遍历整个树

全部评论

相关推荐

10-17 12:16
同济大学 Java
7182oat:快快放弃了然后发给我,然后让我也泡他七天最后再拒掉,狠狠羞辱他一把😋
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务