牛客-剑指offer系列题解:二叉搜索树的第k个结点

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值