本题其实难度并不高,我也看出了解题思路,就是用树的inorder traversal,但是细节处理上出了问题。
    关键点就是设置一个全局变量count,来追踪target,每遇到一个node,就自减1即可,本题可说的并不多,直接看代码会更清晰

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. private static int count;
    12. private static TreeNode target;
    13. public int kthSmallest(TreeNode root, int k) {
    14. count = k;
    15. inorder(root);
    16. return target.val;
    17. }
    18. private void inorder(TreeNode node) {
    19. if (node.left != null) {
    20. inorder(node.left);
    21. }
    22. --count;
    23. if (count == 0) {
    24. target = node;
    25. }
    26. if (node.right != null) {
    27. inorder(node.right);
    28. }
    29. }
    30. }