Share my simple preorder java code


  • 0
    M
    public class Solution {
    private int kth = 0;
    private int a = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        a = k;    
        helper(root);
        return kth;
        
        
    }
    
    private void helper(TreeNode root)    {
        if(root == null || a == 0) // once we get the answer, a=0, so we can return to main function quick
            return;
        helper(root.left);
        a--;
        if(a == 0)
            kth = root.val;
        helper(root.right);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.