LeetCode-230. Kth Smallest Element in a BST
2016-02-19 22:29
465 查看
Description:
Given a binary search tree, write a function
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
题意:从二叉查找树中找第k小的数。
思路:中序遍历,找到第k个便是。
C++:
LeetCode很奇怪,同样的代码Java却过不了。。。还是1 null 2 ,2这个数据过不了,我自己测试的都能过。。。。
更新----------------
终于找到原因了,原来我用了静态变量,后台测试连续调用,结果不清零。。。
最终Java代码:
Given a binary search tree, write a function
kthSmallestto 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); } }
相关文章推荐
- 人生的第一篇博客!
- (8) linux shell 命令 -- cp
- codeforces 630K Indivisibility (容斥原理)
- vmware 连接外部设备
- ubuntu 10.04 usb wifi 使用wpa_supplicant无法连网问题
- 生产者消费者模式学习
- SQL 插入日期时间 变量值
- 定制化Azure站点Java运行环境(3)
- hrbust 哈理工oj 1570 田忌赛马【贪心】
- 快速傅里叶变换
- 在win10上安装nodejs+npm+express+coffeescript
- 定制化Azure站点Java运行环境(2)
- json错误(没有转化为javascript的错误)
- Android本地数据安全尝试(上)——SQLCipher
- 16-02-19 ListView 属性
- 【POJ】2031 - Building a Space Station(克鲁斯塔尔)
- Java TCP 简单实例
- [Android] Android5.1系统自带的应用启动次数统计
- SQL Developer报错:Unable to find a Java Virtual Machine解决办法
- MySQL索引背后的数据结构及算法原理