题解 | #二叉搜索树的第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) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param proot TreeNode类 
     * @param k int整型 
     * @return int整型
     */
    
    int KthNode(TreeNode* proot, int k) {
        int count = 0;
        return KthNode2(proot, k, count);
    }

    int KthNode2(TreeNode *proot, int k, int &count) {
        if (!proot) {
            return -1;
        }
        int l = KthNode2(proot->left, k, count);
        if (l != -1) {
            return l;
        }
        ++count;
        if (count == k) {
            return proot->val;
        }
        return KthNode2(proot->right, k, count);
    }
};

思路:二叉搜索树中序遍历即为顺序遍历,所以中序遍历并计数即可。

全部评论

相关推荐

抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务