Easy inorder traversal Java code without extra space


  • -4
    W

    public int kthSmallest(TreeNode root, int k) {
    if(root==null) return 0;
    int [] kk=new int[1];
    kk[0]=0;
    int [] value=new int[1];
    kthSmallestHelper(root, k, kk, value);
    return value[0];

    }
    
    public void kthSmallestHelper(TreeNode root, int k, int[] kk, int[] value) {
        
        if(kk[0]==k) {
            return;
        }
        if(root.left!=null)
            kthSmallestHelper(root.left, k,kk, value); 
    
        kk[0]++;
        if(kk[0]==k) { 
            value[0]=root.val;
            return;
        }
        
        if(root.right!=null) 
            kthSmallestHelper(root.right, k,kk, value);
            
    }

Log in to reply
 

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