首页 > 其他 > 详细

9-230. Kth Smallest Element in a BST

时间:2019-05-29 00:29:10      阅读:156      评论:0      收藏:0      [点我收藏+]

题目描述:

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小的数。

9-230. Kth Smallest Element in a BST

原文:https://www.cnblogs.com/tbgatgb/p/10941272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!