leetcode-python-二叉搜索树中第K小的元素

时间:2021-06-25 16:32:21   收藏:0   阅读:0

逐行入栈,排序后直接输出第k小的数据

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        if not root:
            return None
        allTree = [root]
        allVal = list()
        while allTree:
            p = allTree[0]
            allVal.append(p.val)
            if p.left:
                allTree.append(p.left)
            if p.right:
                allTree.append(p.right)
            del allTree[0]
        allVal.sort()
        return allVal[k-1]

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!