LeetCode-230. Kth Smallest Element in a BST
Description:
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.
题意:从二叉查找树中找第k小的数。
思路:中序遍历,找到第k个便是。
C++:
class Solution { public: int num=0;//记录次数 int re;//记录最终结果 //中序遍历的方法 void digui(TreeNode* root, int k) { if(root->left!=NULL) digui(root->left,k); num++; if(num==k) re=root->val; if(root->right!=NULL) digui(root->right,k); return; } int kthSmallest(TreeNode* root, int k) { digui(root,k); return re; } };
LeetCode很奇怪,同样的代码Java却过不了。。。还是1 null 2 ,2这个数据过不了,我自己测试的都能过。。。。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public static int cnt = 0; public static int ans; public int kthSmallest(TreeNode root, int k) { travels(root, k); return ans; } public void travels(TreeNode node, int k) { if(node.left != null) travels(node.left, k); cnt ++; if(cnt == k) { ans = node.val; } if(node.right != null) travels(node.right, k); } }
更新----------------
终于找到原因了,原来我用了静态变量,后台测试连续调用,结果不清零。。。
最终Java代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int cnt = 0; public int ans; public int kthSmallest(TreeNode root, int k) { travels(root, k); return ans; } public void travels(TreeNode node, int k) { if(node == null) return ; travels(node.left, k); cnt ++; if(cnt == k) { ans = node.val; return ; } travels(node.right, k); } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)