• 230. 二叉搜索树中第K小的元素


    给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

    说明:
    你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

    示例 1:

    输入: root = [3,1,4,null,2], k = 1
    3
    /
    1 4

      2
    输出: 1
    示例 2:

    输入: root = [5,3,6,2,4,null,null,1], k = 3
    5
    /
    3 6
    /
    2 4
    /
    1
    输出: 3

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst

    1)二叉搜索树的性质,root 大于左子树,小于右子树,如果左子树的节点是 k-1,那么 root 就是结果,否则如果左子树节点数目小于 K-1,那么结果就在右子树,否则就在左子树。

    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @param {number} k
     * @return {number}
     */
    function Count(node){
        if(node===null)return 0;
        const l=Count(node.left);
        const r=Count(node.right);
        return l+r+1;
    }
    var kthSmallest = function(root, k) {
        const l=Count(root.left);
        if(l===k-1)return root.val;
        else if(l<k-1)return kthSmallest(root.right,k-l-1);
        return kthSmallest(root.left,k);
    };

    2)中序遍历一个二叉查找树(BST)的结果是一个有序数组,因此只需要在遍历到第k个,返回当前元素即可

    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @param {number} k
     * @return {number}
     */
    var kthSmallest = function(root, k) {
        const stack=[root];
        let cur=root;
        let i=0;
    
        function insertLefts(cur){
            while(cur&&cur.left){
                const l=cur.left;
                stack.push(l);
                cur=l;
            }
        }
        insertLefts(cur);
    
        while(cur=stack.pop()){
            i++;
            if(i===k)return cur.val;
            const r=cur.right;
            if(r){
                stack.push(r);
                insertLefts(r);
            }
        }
        return -1;
    };
  • 相关阅读:
    fabrci网络调优
    fabric链码容器
    fabric文档查阅
    fabric基础设施管理-(五)移除网络
    fabric源码编译
    fabric网络状态监控
    fabric基础设施管理-(六)配置管理
    Scheme宏基础入门(转载)
    GO语言程序中解决中文日期格式的解析问题
    临别之际
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13304954.html
Copyright © 2020-2023  润新知