剑指offer62.二叉搜索树的第k个结点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/87931553

给定一棵二叉搜索树,请找出其中的第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:
    def __init__(self):
        self.index = 0

    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        if pRoot:
            left = self.KthNode(pRoot.left, k)
            if left:
                return left
            self.index += 1
            if self.index == k:
                return pRoot
            right = self.KthNode(pRoot.right, k)
            if right:
                return right
        return None

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/87931553