剑指offer面试54题

面试54题:

题目:二叉搜索树的第K大节点

题:给定一颗二叉搜索树,请找出其中的第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 KthNode(self, pRoot, k):
        # write code here
        if not pRoot or k<=0:
            return None
        res=[]
        
        def inorder(pRoot):
            if not pRoot:
                return []
            inorder(pRoot.left)
            res.append(pRoot)
            inorder(pRoot.right)
        inorder(pRoot)
        if len(res)<k:
            return None
        return res[k-1]
原文地址:https://www.cnblogs.com/yanmk/p/9232796.html