230. Kth Smallest Element in a BST

leetcode

Posted by chl on May 18, 2019

题目

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返回即可

代码

var count = 0
func kthSmallest(root *TreeNode, k int) int {
    if root==nil{
        return -1
    }
    
    l := kthSmallest(root.Left,k)
    if l!=-1{
        return l
    }
    count++
    if count == k{
        count=0
        return root.Val
    }
    r := kthSmallest(root.Right,k)
    if r!=-1{
        return r
    }
    
    return -1
}

总结

leetcode的中等题真实难易跨度挺大的。这道题怎么说也应该是简答题吧。中序遍历就好了。但是在leetcode上要注意全局变量。每一次测试都会保留上一个值