题目描述
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.
例子
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
解释
给一个二叉搜索树,找到其中第k小的元素。
思路 中序遍历
看到二叉搜索树,就想到其性质:左孩子<根<右孩子。因此中序遍历后的数组,一定是有序的。我们用中序遍历,将节点的值存入数组中,最后返回数组的第k个元素即可。
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
self.tree = []
self.inorder(root)
return self.tree[k - 1]
def inorder(self, root):
if not root:
return
if root.left:
self.inorder(root.left)
self.tree.append(root.val)
if root.right:
self.inorder(root.right)