Description:
Given A binary search tree, write a function to kthSmallest find the kth smallest element in it.
Note:
You may assume k are always valid, 1≤k≤bst's total elements.
Test instructions: Find the small number of k from the two-fork search tree.
Train of thought: the middle sequence traversal, found the first k is.
C++:
classSolution { Public: intnum=0;//number of recordsintRe//record the final result//The method of middle sequence traversalvoidDigui (treenode* root,intk) { if(root->left!=NULL) Digui (Root-left,k); Num++; if(num==k) Re=root->Val; if(root->right!=NULL) Digui (Root-right,k); return;} intKthsmallest (treenode* root,intk) {Digui (root,k); returnre; }};
Leetcode very strange, the same code Java can not get over ... or 1 null 2, 2 This data is not enough, I can test all the ....
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public Static intCNT = 0; Public Static intans; Public intKthsmallest (TreeNode root,intk) {Travels (root, k); returnans; } Public voidTravels (TreeNode node,intk) {if(Node.left! =NULL) Travels (Node.left, k); CNT++; if(CNT = =k) {ans=Node.val; } if(Node.right! =NULL) Travels (Node.right, k); }}
Update----------------
Finally found the reason, I used a static variable, background test Continuous Call, the results are not clear zero ...
Final Java code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public intCNT = 0; Public intans; Public intKthsmallest (TreeNode root,intk) {Travels (root, k); returnans; } Public voidTravels (TreeNode node,intk) {if(node = =NULL) return ; Travels (Node.left, k); CNT++; if(CNT = =k) {ans=Node.val; return ; } Travels (Node.right, k); }}
LeetCode-230. Kth smallest Element in a BST