leetcode_230题——Kth Smallest Element in a BST(二叉搜索树,中序遍历)

Kth Smallest Element in a BST

  Total Accepted: 7584 Total Submissions: 25621My Submissions

 

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?

Show Hint 

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

     

    Hide Tags
      Tree Binary Search
    Hide Similar Problems
      (M) Binary Tree Inorder Traversal
    Have you met this question in a real interview? 
    Yes
     
    No
     

    Discuss

          这道题采用中序遍历的方法,在遍历时记录下遍历的第几个就可以了

    #include<iostream>
    using namespace std;
    struct TreeNode {
          int val;
          TreeNode *left;
          TreeNode *right;
          TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     };
    int num=0;//记录次数
    int re;//记录最终结果
    
    //中序遍历的方法
    void digui(TreeNode* root, int k)
    {
        if(root->left!=NULL)
            digui(root->left,k);
        num++;
        if(num==k)
            re=root->val;
        if(root->right!=NULL)
            digui(root->right,k);
        return;
    }
    
    int kthSmallest(TreeNode* root, int k) {
        digui(root,k);
        return re;
    }
    int main()
    {
    
    }

     

    你可能感兴趣的:(LeetCode)