zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    Tor网络突破IP封锁,爬虫好搭档【入门手册】
    ubuntu python3相关
    toutiao url
    处理跨域请求
    Python使用虚拟环境
    Python删除文件,空文件夹,非空文件夹
    如何在jupyter中使用Python2和Python3
    推荐使用国内的豆瓣源安装Python插件
    Python数据库查询之组合条件查询-F&Q查询
    获取Django项目的全部url
  • 原文地址:https://www.cnblogs.com/skillking/p/9928164.html
Copyright © 2011-2022 走看看