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 kthSmallest(self, root: TreeNode, k: int) -> int:
def mid(root,k):
if not root:
return []
return mid(root.left,k-1) + [root.val] + mid(root.right,k-1)
return mid(root,k)[k-1]
解法二:直接统计到第k个数即可,始终没有return操作;
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.res = 0
self.cnt = 0
self.mid(root,k)
return self.res
def mid(self,root,k):
if root.left:
self.mid(root.left,k)
self.cnt += 1
if self.cnt == k:
self.res = root.val
if root.right:
self.mid(root.right,k)