首页 > 其他分享 >leetcode-230. 二叉搜索树中第K小的元素

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

时间:2023-01-08 21:46:11浏览次数:63  
标签:TreeNode int 230 dfs num ans root 树中 leetcode

dfs 中序遍历即可

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

var num, ans int
var find bool


func kthSmallest(root *TreeNode, k int) int {
    find = false
    num, ans = 0, 0

    dfs(root, k)
    return ans
}

func dfs(root *TreeNode, k int) {
    if find || root == nil {
        return
    }

    if root.Left != nil {
        dfs(root.Left, k)
    }

    num++

    if num == k {
        ans = root.Val
        find = true
    }

    if root.Right != nil {
        dfs(root.Right, k)
    }

    return
}

参考

230. 二叉搜索树中第K小的元素 - 力扣(Leetcode)

题解中有后续优化的解法

题解-230. 二叉搜索树中第K小的元素 - 力扣(Leetcode)

标签:TreeNode,int,230,dfs,num,ans,root,树中,leetcode
From: https://www.cnblogs.com/wudanyang/p/17035453.html

相关文章

  • 230108_50_RPC底层原理
    Stub还有很多需要优化的地方,目前只是实现了一个最基本的代理。网络传输都是通过序列化和反序列化进行的,目前java自带的Serializable接口效率比较低,因此可以对rpc的序列化......
  • leetcode-671. 二叉树中第二小的节点
    dfs取左右子树第二大的值进行比较/***Definitionforabinarytreenode.*typeTreeNodestruct{*Valint*Left*TreeNode*Right*TreeNod......
  • leetcode-2185. 统计包含给定前缀的字符串
    简单题,重拳出击funcprefixCount(words[]string,prefstring)int{validCnt:=0for_,w:=rangewords{notValid:=falseiflen(w)......
  • leetcode-409-easy
    LongestPalindromeGivenastringswhichconsistsoflowercaseoruppercaseletters,returnthelengthofthelongestpalindromethatcanbebuiltwiththose......
  • leetcode-345-easy
    ReverseVowelsofaStringGivenastrings,reverseonlyallthevowelsinthestringandreturnit.Thevowelsare'a','e','i','o',and'u',andtheycan......
  • leetcode-643-easy
    MaximumAverageSubarrayIYouaregivenanintegerarraynumsconsistingofnelements,andanintegerk.Findacontiguoussubarraywhoselengthisequalto......
  • leetcode-496-easy
    NextGreaterElementIThenextgreaterelementofsomeelementxinanarrayisthefirstgreaterelementthatistotherightofxinthesamearray.Youar......
  • leetcode-521-easy
    LongestUncommonSubsequenceIGiventwostringsaandb,returnthelengthofthelongestuncommonsubsequencebetweenaandb.Ifthelongestuncommonsubseq......
  • leetcode-551-easy
    StudentAttendanceRecordIYouaregivenastringsrepresentinganattendancerecordforastudentwhereeachcharactersignifieswhetherthestudentwasab......
  • leetcode-485-easy
    MaxConsecutiveOnesGivenabinaryarraynums,returnthemaximumnumberofconsecutive1'sinthearray.Example1:Input:nums=[1,1,0,1,1,1]Output:3E......