我正在从leetcode解决这个问题,并为此自己写了一些代码。我按照这里提到的想法: find-kth-smallest-element-in-a-binary-search-tree-in-optimum-way
看起来它没有返回正确的结果,我需要一些关于这个逻辑可能出错的反馈。有人可以在这里提供一些见解吗?如果可能的话,尝试用我使用的相同方法解释你的答案,这样就更容易理解我哪里出错了。谢谢!
这是我的代码:
/**
* 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 kthSmallest(TreeNode root, int k) {
//what happens if root == null
//what happens if k > total size of tree
return kthSmallestNode(root,k).val;
}
public static TreeNode kthSmallestNode(TreeNode root,int k){
if(root==null) return root;
int numberOfNodes = countNodes(root.left);
if(k == numberOfNodes ) return root;
if(k<numberOfNodes ) return kthSmallestNode(root.left,k);
else return kthSmallestNode(root.right,k-numberOfNodes );
}
private static int countNodes(TreeNode node){
if(node == null) return 0;
else return 1+countNodes(node.left)+countNodes(node.right);
}
}
自定义测试用例:
TreeNode - [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
k = 3
My Answer - 8
Expected Answer - 17 (This is as per leetcode)