标签:函数 init roo end iar 排列 append ret def
题目:
二叉搜索树中第K小的元素:给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 说明: 你可以假设 k 总是有效的,1 ≤ 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:
auxiliary = []
def inorder(root, auxiliary):
if root == None:
return auxiliary
inorder(root.left, auxiliary)
auxiliary.append(root.val)
inorder(root.right, auxiliary)
inorder(root, auxiliary)
result = auxiliary[k - 1]
return result
标签:函数 init roo end iar 排列 append ret def
原文地址:https://www.cnblogs.com/zhuozige/p/12875533.html