zoukankan      html  css  js  c++  java
  • LeetCode 230. Kth Smallest Element in a BST(寻找二叉查找树的第 k 个元素)

    题意:寻找二叉查找树的第 k 个元素。

    法一:中序遍历

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int ans = -1;
        int cnt = 0;
        int kthSmallest(TreeNode* root, int k) {
            inOrder(root, k);
            return ans;
        }
        void inOrder(TreeNode* root, int k){
            if(root == NULL) return;
            inOrder(root -> left, k);
            ++cnt;
            if(cnt == k){
                ans = root -> val;
                return;
            }
            inOrder(root -> right, k);
        }
    };
    

    法二:二分  

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            int leftcnt = count(root -> left);
            if(leftcnt == k - 1) return root -> val;
            else if(leftcnt > k - 1) return kthSmallest(root -> left, k);
            else return kthSmallest(root -> right, k - leftcnt - 1);
        }
        int count(TreeNode* root){
            if(root == NULL) return 0;
            return count(root -> left) + count(root -> right) + 1;
        }
    };
    

      

  • 相关阅读:
    Eclipse项目上传和下载到码云上
    java.lang.IllegalArgumentException,java.util.zip.ZipException 解决办法
    #{}和${}的区别
    Lambda 表达式
    存储器的按字寻址和按字节寻址
    二叉树的三种遍历方式
    线性表和链表
    java泛型理解
    java字符输入输出流
    applet的生命周期
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12537188.html
Copyright © 2011-2022 走看看