Java Solution with Inorder Traversing using Stack, easy to understand.


  • 3
    public class Solution {
    private Stack<TreeNode> s;
    public int kthSmallest(TreeNode root, int k) {
        s=new Stack<TreeNode>();
        if(root==null)  return 0;
        
        pushLeft(root);
        while(!s.empty()){
           
            TreeNode tn=s.pop();
            if(--k==0)
                return tn.val;
            if(tn.right!=null)  
                pushLeft(tn.right);
        }
        return 0;
    }
    private void pushLeft(TreeNode root){
        
        s.push(root);
        TreeNode p=root.left;
        while(p!=null){
            s.push(p);
            p=p.left;
            
        }
    }
    

    }


Log in to reply
 

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