Golang Leetcode 230. Kth Smallest Element in a BST.go

时间:2022-06-19
本文章向大家介绍Golang Leetcode 230. Kth Smallest Element in a BST.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89043444

思路

先计算左子树中节点的个数 如果左子树节点个数大于k-1,那么答案在左子树中 如果个数小于k-1,就在右子树中 如果刚好相等,就直接返回root节点的值

code

func kthSmallest(root *TreeNode, k int) int {
	left := countLeaf(root.Left)
	if left == k-1 {
		return root.Val
	} else if left > k-1 {
		return kthSmallest(root.Left, k)
	} else {
		return kthSmallest(root.Right, k-left-1)
	}
}

func countLeaf(root *TreeNode) int {
	if root == nil {
		return 0
	}
	return countLeaf(root.Left) + countLeaf(root.Right) + 1
}