230.二叉搜索树中第K小的元素

难度:中等
题目描述:
230.二叉搜索树中第K小的元素_第1张图片
思路总结:偷个小懒,用中序遍历出二叉搜索树的序列,然后直接返回下标。
题解一:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        res = []
        stack = deque()
        cur = root
        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        return res[k-1]

题解一结果:

你可能感兴趣的:(朱滕威的面试之路)