解题思路:
深度优先搜索,采用中序遍历的方式,然后找到第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:
my_list = []
self.dfs(root, my_list)
return my_list[k-1]
def dfs(self, root, my_list):
if not root:
return
else:
self.dfs(root.left, my_list)
my_list.append(root.val)
self.dfs(root.right, my_list)