记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
2、数据结构:
二叉树,深度优先搜索
3、题解:
二叉搜索树的中序遍历是有序的(升序)所以用中序遍历去做即可
递归写法:
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
res = []
def dfs(root):
if not root:
return
dfs(root.left)
res.append(root)
dfs(root.right)
dfs(pRoot)
if len(res) < k or k < 1:
return None
return res[k-1]
非递归写法:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
res = []
def midorder(root):
if not root:
return
stack = []
temp = root
while temp or stack:
while temp:
stack.append(temp)
temp = temp.left
node = stack.pop()
res.append(node)
temp = node.right
midorder(pRoot)
if len(res) < k or k < 1:
return None
return res[k-1]
4、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)