1. 程式人生 > >#Leetcode# 230. Kth Smallest Element in a BST

#Leetcode# 230. Kth Smallest Element in a BST

https://leetcode.com/problems/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

程式碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <iostream>
using namespace std;

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        if(!root) return 0;
        vector<int> ans;
        pre(root, ans);
        sort(ans.begin(), ans.end());    
        if(k > ans.size()) return 0;
        else return ans[k - 1];
    }
    void pre(TreeNode* root, vector<int>& ans) {
        if(root) {
            ans.push_back(root -> val);
            if(root -> left != NULL) 
                pre(root -> left, ans);
            if(root -> right != NULL)
                pre(root -> right, ans);
        }
    }
};

  FH 沒看出來的 bug 那麼這個算是我自己改出來的!!!