思路:刚开始没看清题目说的是二叉搜索树,以为是普通的二叉树,便想着直接BFS,再排下序,就完了。后来看见是二叉搜索树,便用中序遍历,遍历到第K个结点就是答案。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int temp = 0;
int count = 0;
public int kthSmallest(TreeNode root, int k) {
count = k;
inOrderTraversal(root);
return temp;
}
public void inOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
inOrderTraversal (root.left);
if (--count == 0) {
temp = root.val;
return;
}
inOrderTraversal (root.right);
}
}