剑指offer - 二叉搜索树第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:
    def KthNode(self, root, k):
        #相当于中序遍历,遍历到的第k个点
        if k<=0 or not root:
            return None
        
        index = 0
        nodes = []
        while 1:
            while 1:
                while root.left:
                    nodes.append(root)
                    root = root.left
                index += 1
                if index == k:
                    return root
                if root.right:
                    root = root.right
                else:
                    break
            if len(nodes)>0:
                root = nodes.pop()
                index += 1
                if index == k:
                    return root
                while root.right == None and len(nodes)>0:
                    root = nodes.pop()
                    index += 1
                    if index == k:
                        return root
                if root.right:
                    root = root.right
                else:
                    break
            else:
                break
        return None
发布了82 篇原创文章 · 获赞 2 · 访问量 4344

猜你喜欢

转载自blog.csdn.net/qq_22498427/article/details/104983098