Kth Smallest Element in a BST Solutions in C++
Number 230
Difficulty Medium
Acceptance 60.4%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/// Author : Hao Chen// Date : 2015-07-03/*** 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 {public:// in-order travel - recursive wayint kthSmallestHelper_recursive(TreeNode* root, int& k) {if (root==NULL) return 0; //this behavior is undefined!//in-order travelint result = kthSmallestHelper_recursive(root->left, k);if (k==0) return result;k--;if (k==0) return root->val;return kthSmallestHelper_recursive(root->right, k);}// in-order travel - non-recursive wayint kthSmallestHelper_nonRecursive(TreeNode* root, int k){stack<TreeNode*> s;while(!s.empty() || root){while (root) {s.push(root);root = root->left;}k--;root = s.top()->right;if (k==0) return s.top()->val;s.pop();}return -1;}int kthSmallest(TreeNode* root, int k) {//return kthSmallestHelper_nonRecursive(root, k);return kthSmallestHelper_recursive(root, k);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/kth-smallest-element-in-a-bst/description//// Author : liuyubobobo/// Time : 2018-07-29#include <iostream>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Inorder Traversal/// Time Complexity: O(n)/// Space Complexity: O(h) where h is the height of the BSTclass Solution {private:int index;public:int kthSmallest(TreeNode* root, int k) {index = 0;return kthSmallestNode(root, k)->val;}private:TreeNode* kthSmallestNode(TreeNode* node, int k){if(node == NULL)return NULL;TreeNode* res = kthSmallestNode(node->left, k);if(res) return res;index ++;if(index == k)return node;return kthSmallestNode(node->right, k);}};int main() {return 0;}