JZ54 二叉搜索树的第k个节点

JZ54 二叉搜索树的第k个节点,第1张

描述

给定一棵结点数为n 二叉搜索树,请找出其中的第 k 小的TreeNode结点值。
1.返回第k小的节点值即可
2.不能查找的情况,如二叉树为空,则返回-1,或者k大于n等等,也返回-1
3.保证n个节点的值不一样

数据范围: 0 \le n \le10000≤n≤1000,0 \le k \le10000≤k≤1000,树上每个结点的值满足0 \le val \le 10000≤val≤1000
进阶:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)

如输入{5,3,7,2,4,6,8},3时,二叉树{5,3,7,2,4,6,8}如下图所示:

该二叉树所有节点按结点值升序排列后可得[2,3,4,5,6,7,8],所以第3个结点的结点值为4,故返回对应结点值为4的结点即可。

示例1
输入:
{5,3,7,2,4,6,8},3
返回值:
4

示例2
输入:
{},1
返回值:
-1
备注:
当树是空

思路

二叉搜索树按照二叉树中序遍历后的结果就是按升序排序好的结果。

代码
/**
 * 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) {
        // write code here
        if (proot == NULL || k <= 0) {
            return -1;
        }
        int res = -1;
        int count = 0;
        midNode(proot, count, k, res);
        return res;
    }
    // count用于记录当前遍历到的节点位置,res用于存储结果
    void midNode(TreeNode *proot, int &count, int k, int &res) {
        if (proot == NULL) {
            return;
        }
        if (proot->left != NULL) {
            midNode(proot->left, count, k, res);
        }
        count = count + 1;
        if (count == k) {
            res = proot->val;
            return;
        }
        if (proot->right != NULL) {
            midNode(proot->right, count, k, res);
        }
    }
};
参考

https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff?tpId=13&tqId=2305268&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1354257.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-14
下一篇2022-06-14

发表评论

登录后才能评论

评论列表(0条)

    保存