Leetcode 230 Kth Smallest Element in a BST, leetcodekth
1. Problem Description
Given a binary search tree, find the smallest k element.
Note: k always exists, 1 ≤ k ≤ BST total number of elements .
2. methods and ideas
Based on the characteristics of the Binary Search Tree, the result of the Middle-order traversal is a sorted array. To find the number smaller than k, you only need to traverse it in a central order first.
/*** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode * left; * TreeNode * right; * TreeNode (int x): val (x), left (NULL), right (NULL) {} *}; */class Solution {private: vector <int> v; void midorder (TreeNode * root) {if (root! = NULL) {midorder (root-> left); v. push_back (root-> val); midorder (root-> right) ;}} public: int kthSmallest (TreeNode * root, int k) {midorder (root ); return v [k-1];};
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.