Leetcode腾讯精选_编号:230 --java
2019-03-01 23:13
417 查看
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 3
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int count; public int kthSmallest(TreeNode root, int k) { int res=0; if (root == null) { return res; } res=kthSmallest(root.left,k); if (count==k) { return res; } count++; if (count==k) { return root.val; } return kthSmallest(root.right, k); } }
相关文章推荐
- Leetcode腾讯精选_编号:344 --python
- Leetcode腾讯精选_编号:557 --python
- Leetcode腾讯精选_编号:231 --python
- Leetcode腾讯精选_编号:235 --python
- Leetcode腾讯精选_编号:236 --python
- Leetcode腾讯精选_编号:237 --python
- Leetcode腾讯精选_编号:292 --python
- 阿里、华为、腾讯Java技术面试题精选
- java 最新面试题 (腾讯 百度 阿里巴巴 华为)精选
- 阿里、华为、腾讯、京东、百度Java技术面试题精选
- Java for LeetCode 230 Kth Smallest Element in a BST
- 阿里、华为、腾讯Java技术面试题精选
- leetcode-230-二叉搜索树中第K小的元素(kth smallest element in a bst)-java
- LeetCode 230 -Kth Smallest Element in a BST ( JAVA )
- [leetcode-230]Kth Smallest Element in a BST(java)
- 阿里、华为、腾讯Java技术面试题精选
- 精选30道Java笔试题解答
- LeetCode 86(Partition List)java
- leetcode-java.T001_TwoSum 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字
- [leetcode]8. String to Integer (atoi)(Java)