leetcode230

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int KthSmallest(TreeNode root, int k)
        {
            int count = countNodes(root.left);
            if (k <= count)
            {
                return KthSmallest(root.left, k);
            }
            else if (k > count + 1)
            {
                return KthSmallest(root.right, k - 1 - count); // 1 is counted as current node
            }

            return root.val;
        }

        public int countNodes(TreeNode n)
        {
            if (n == null) return 0;

            return 1 + countNodes(n.left) + countNodes(n.right);
        }
}

https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/description

时间: 2024-08-08 14:38:12

leetcode230的相关文章

leetcode-230

leetcode-230 题目描述: 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 解法一,其实就是中序遍历,刚开始不知道怎么统计到第k个数 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def kt

LeetCode-230. Kth Smallest Element in a BST

Description: Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 题意:从二叉查找树中找第k小的数. 思路:中序遍历,找到第k个便是. C++: class Solution { public: int n

8.3 LeetCode230 Return the kth smallest element of a BST

Kth Smallest Element in a BST Total Accepted: 9992 Total Submissions: 33819My Submissions Question Solution Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k

树—最“有套路”的数据结构

前言 标题用“有套路”来形容一种数据结构,似乎有点不尊重的意思.不过,我倒是觉得,一种实用的学科,就是应该产生一点套路,这才能发挥体系化研究的优势,套路就是一种保证:在不投入更多创造性与努力的情况下,依旧能获得比起随意进行相关操作更好的结果.一门成熟的学科都应如是,如果研究许久,在学科所研究的许多问题的实践上还不如一些“天赋”“灵感”,那就不得不说这门学科的“伪科学”或者“水分”还是蛮大的了. 言归正传,这篇文章将会是一系列寻找算法与数据结构的文章的开篇,树由于其特性,是递归.分治等等重要算法思