给定一颗二叉搜索树,请找出其中的第k小的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
基本思路:一个中序遍历的问题。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def __init__(self):
self.counter = 0
self.p = None
def KthNode(self, pRoot, k):
# write code here
if pRoot:
self.KthNode(pRoot.left, k)
self.counter += 1
if self.counter == k:
self.p = pRoot
self.KthNode(pRoot.right, k)
return self.p
也可以不设置p这样的变量,在两次递归调用的代码后面分别判断当前返回值是否为空,不为空就返回。
本文介绍了一种寻找二叉搜索树中第K小结点的方法,通过中序遍历,确保了访问顺序为升序排列,进而找到指定的结点。
1747

被折叠的 条评论
为什么被折叠?



