• 230. Kth Smallest Element in a BST


    一、题目

      1、审题

      

      2、分析

        给出一棵二分查找树,求出其中第 k 小的节点数值。

    二、解答

      1、思路

        方法一、 

          使用 Stack 进行中序遍历。若常访问,则可以采用一个 List 存储。

        public int kthSmallest2(TreeNode root, int k) {
            int count = 0;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode cur = root;
            // 经常访问的话,放在 List 中记录
            List<Integer> list = new ArrayList<>();
            while(!stack.isEmpty() || cur != null) {
                while(cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                }
                
                cur = stack.pop();
                list.add(cur.val);
                if(++count == k)
                    return cur.val;
                cur = cur.right;
            }
            return -1;
        }

      

      方法二、

        采用二分查找。

        ①、先统计左子树长度 m,若 k < m + 1,则要查找的元素在左子树中。

        ②、若 k == m + 1,则要查找的元素是根节点。

        ③、若 k > m + 1,则要查找的元素在右子树。

        // Binary Search
        public int kthSmallest3(TreeNode root, int k) {
            int count = helpCountNodes(root.left);
    
            if(k < count + 1)
                return kthSmallest(root.left, k);
            else if(k == count + 1)
                return root.val;
            else 
                return kthSmallest(root.right, k - 1 - count);
        }
        
        private int helpCountNodes(TreeNode node) {
            if(node == null)
                return 0;
            return 1 + helpCountNodes(node.left) + helpCountNodes(node.right);
        }
  • 相关阅读:
    Windows phone 7 OpenSource Project
    编程之美阅读笔记
    Java多线程中读写不一致问题
    pytorch性能瓶颈检查
    贪心会议安排
    网络编程之libevent
    笔记:自动求导【动手学深度学习v2】
    测试
    AnimeGAN+Flask部署过程
    手写哈希表
  • 原文地址:https://www.cnblogs.com/skillking/p/9928164.html
Copyright © 2020-2023  润新知