Share my java solution


  • 0
    A
    public class Solution {
        int re = 0;
        int kk = 0;
        public int kthSmallest(TreeNode root, int k) {
            kk = k;
            helper(root);
            return re;
        }
        private void helper(TreeNode root){
            if(root==null) return;
            helper(root.left);
            if(--kk==0)
                re = root.val;
            helper(root.right);
        }
    }

  • 0
    J

    If you return when kk==0, then you don't have to traverse on the right, right? Something like:

    private void helper(TreeNode root){
    if(root==null) return;
    helper(root.left);
    if(--kk==0) {
    re = root.val;
    return;
    }
    helper(root.right);
    }


  • 0
    Z

    I throw a exception to avoid visit right nodes when kth smallest value is found.

    public class Solution {
    int k = 0;
    int value = 0;
    
    public int kthSmallest(TreeNode root, int k) {
    this.k = k;
    try {
        inOrder(root);
    } catch (Exception e) {
    }
    return value;
    }
    
    void inOrder(TreeNode node) throws Exception {
    if (node == null)
        return;
    inOrder(node.left);
    if (--k == 0) {
        value = node.val;
        throw new Exception();
    }
    inOrder(node.right);
    }
    

    }


Log in to reply
 

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