Java Solution, recursive and iterative: )


  • 1

    recursive:

    public class Solution {
        int count = 0;
        int result = 0;
        public int kthSmallest(TreeNode root, int k) {
            
            inOrder(root, k);
            return result;
          
        }
        public void inOrder(TreeNode root, int k){
            
            if(root != null){
                inOrder(root.left, k);
                if(++count == k){
                   result = root.val;
                   return;
                }
                inOrder(root.right, k);
            }
        }
    }`
    
    

    iterative:

    public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<>();
            int count = 0;
            
            while(root != null || !stack.empty()){
                
                while(root != null){
                    
                    stack.push(root);
                    root = root.left;
                }
                if(!stack.empty()){
                    
                    root = stack.pop();
                    if(++count == k)
                        return root.val;
                    
                    root = root.right;
                }
            }
            return 0;
        }
    

Log in to reply
 

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