牛客网-Python-二叉搜索树的第k个节点

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

思路

二叉搜索树的中序遍历是一个递增数列。因此在中序遍历的过程中计数即可找到第k小的节点。

代码

# -*- 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
        if not pRoot:
            return None
        if k<=0:
            return
        count = 0
        stack = []
        root = pRoot
        while stack or root!=None:
            #节点不空,不断加左节点
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            count += 1
            if count == k:
                return root
            #***********这里不能判断右子树不空。空子树是出栈的时间!
            root = root.right

我没用递归做,leileleile

原文地址:https://www.cnblogs.com/ditingz/p/12300593.html