Given A binary search tree, write a function to kthSmallest
find the k-th smallest element in it.
Note:
You may assume k are always valid, 1≤k≤bst's total elements.
Problem-solving idea: The number of K small in BST (binary sort tree) is obtained. Method One: Traverse the whole binary tree, then sort, output the Val value of the K-node. The code is as follows (where we take the stack, advanced back out, right to left.) First-order traversal of the entire binary tree):
Class Solution {public: int kthsmallest (treenode* root, int k) { if (root==null) return 0; Stack<treenode*> Qu; vector<int> Res; Qu.push (root); while (!qu.empty ()) { treenode* node=qu.top (); Qu.pop (); Res.push_back (node->val); if (node->right!=null) { qu.push (node->right); } if (node->left!=null) { qu.push (node->left); } } Sort (Res.begin (), Res.end ()); return res[k-1];} ;
Method Two:
In a binary search tree, find the K element.
The algorithm is as follows:
1. Count left subtree elements.
2, left+1 = k, the root node is the K element
Left >=k, the first k element is
Left +1 <k, it is converted to the right subtree, looking for the k-left-1 element.
The code is as follows:
Class Solution {public: int treeSize (treenode* root) { if (root==null) return 0; Return 1+treesize (Root->left) +treesize (root->right); } int kthsmallest (treenode* root, int k) { if (root==null) return 0; int leftsize=treesize (root->left); if (k==leftsize+1) return root->val; else if (leftsize>=k) return Kthsmallest (Root->left, k); else return kthsmallest (Root->right, k-leftsize-1); };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Kth smallest Element in a BST