zoukankan      html  css  js  c++  java
  • 9-230. Kth Smallest Element in a BST

    题目描述:

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

    Example 1:

    Input: root = [3,1,4,null,2], k = 1
       3
      / 
     1   4
      
       2
    Output: 1

    Example 2:

    Input: root = [5,3,6,2,4,null,null,1], k = 3
           5
          / 
         3   6
        / 
       2   4
      /
     1
    Output: 3
    

    Follow up:
    What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

    代码实现(他山之石):

     1 # Definition for a binary tree node.
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution:
     9     def kthSmallest(self, root: TreeNode, k: int) -> int:
    10         self.inorder_result = []
    11         
    12         def inorder(root):
    13             if root.left:
    14                 inorder(root.left)
    15                 
    16             self.inorder_result.append(root.val)
    17             
    18             if root.right:
    19                 inorder(root.right)
    20         
    21         inorder(root)
    22         
    23         return self.inorder_result[k-1]

    分析:

    通过inorder函数,从根节点开始,找到最左下角的元素,然后从小到大访问树的每一个节点(并记录每个当前节点的值,存储在inorder_result中的值就是从小到大排列的),直至遍历所有节点。

    最终inorder_result中第k-1个位置上的值就是第k小的数。

  • 相关阅读:
    幸运序列(lucky) 模拟
    無名(noname) 字符串
    香港记者 图论
    Jmeter接口测试系列之参数化方法
    jmeter接口测试-总结
    python字符串
    python变量
    7.15-ROS可视化工具-标记
    6.22-Actionlib
    7.1-Move_base 参数调整
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/10941272.html
Copyright © 2011-2022 走看看