题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
代码
# 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:
res=[]
self._kth(root,res)
return res[k-1]
# 深度遍历,中序
def _kth(self,root,res):
if root.left:
self._kth(root.left,res)
res.append(root.val)
if root.right:
self._kth(root.right,res)
思路解析
进行中序遍历,然后获取第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:
res,cur,cnt=[],root,0
while cur or res:
while cur:
res.append(cur)
cur=cur.left
cur=res.pop()
cnt+=1
if cnt==k :
return cur.val
cur=cur.right
思路详解
先找到最小的节点,然后进行回溯,知道达到k个值