A variation of in-order traversal in Java


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

Log in to reply
 

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