Try   HackMD

【LeetCode】 230. Kth Smallest Element in a BST

Description

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

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?

Constraints:

  • The number of elements of the BST is between 1 to 10^4.
  • You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

給予一個二元搜索樹(BST),寫一個程式kthSmallest可以找出裡面第k小的元素。

進階:
如果這個BST很常被更改(插入/刪除),且你也很常需要找到第k小的元素該怎麼辦?你可以優化到常數時間內嗎?

限制:

  • BST中的元素介於110^4之間。
  • 你可以假設k總是合法,1 ≤ k ≤ BST's total elements

Example:

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

Solution

  • BST中如果要照大小去遍歷,只要跑中序遍歷即可。
  • 因此我們只要跑中序,每次將k--,跑到k == 0的時候將該節點的值取出即可。

  • 進階題還沒有研究,先跳過。

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void InorderTraversal(TreeNode* node, int& k, int& ans) { if(ans != -1) return; if(node) { InorderTraversal(node->left, k, ans); k--; if(k == 0) ans = node->val; InorderTraversal(node->right, k, ans); } } int kthSmallest(TreeNode* root, int k) { int ans = -1; InorderTraversal(root, k, ans); return ans; } };
tags: LeetCode C++