zoukankan      html  css  js  c++  java
  • [LeetCode]Kth Smallest Element in a BST

    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.

    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?

    Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    利用BST的性质,中序遍历得到的就是从小到大的排列,返回第k-1个数字。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void traversal(TreeNode* root,vector<int>& result)
    13     {
    14         if(root)
    15         {
    16             traversal(root->left,result);
    17             result.push_back(root->val);
    18             traversal(root->right,result);
    19         }
    20     }
    21     int kthSmallest(TreeNode* root, int k) {
    22         vector<int> result;
    23         traversal(root,result);
    24         return result[k-1];
    25     }
    26 };
  • 相关阅读:
    (转)关于IBM小机P520的面板使用
    (转)mysql的sql_mode合理设置
    (转)Mysql技术内幕InnoDB存储引擎-事务&备份&性能调优
    杨辉三角
    异或的陷阱(转)
    通过数组看栈堆
    数组的一些知识点和插入选择冒泡排序
    运算符
    Java的变量相关
    有符号的数据表示法(原、反、补)
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4812720.html
Copyright © 2011-2022 走看看