1. 程式人生 > >leetcode 二叉搜尋樹中第K小的元素 python

leetcode 二叉搜尋樹中第K小的元素 python

1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def kthSmallest(self, root, k): 10 """ 11 :type root: TreeNode
12 :type k: int 13 :rtype: int 14 """ 15 # 先廣度優先遍歷 16 width = [root] 17 val = [root.val] 18 i = 0 19 while i < len(width): 20 cur = width[i] 21 if cur.left is not None: 22 width.append(cur.left)
23 val.append(cur.left.val) 24 if cur.right is not None: 25 width.append(cur.right) 26 val.append(cur.right.val) 27 i += 1 28 val.sort() 29 30 return val[k-1] 31 32 33