面试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]

 

相关文章:

  • 2021-09-06
  • 2021-12-23
  • 2021-09-20
  • 2021-09-29
  • 2021-09-21
  • 2022-01-25
  • 2022-02-20
  • 2021-10-06
猜你喜欢
  • 2021-07-23
  • 2021-09-13
  • 2021-11-03
  • 2021-09-20
  • 2021-07-09
  • 2021-12-13
  • 2022-02-26
相关资源
相似解决方案