My Java solution using Stack


  • -1
    B
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> st = new Stack<TreeNode>();
            
            TreeNode temp = root;
            
            while(temp != null){
                st.push(temp);
                temp = temp.left;
            }
            
            TreeNode curr = st.peek();
            
            while(k > 0){
                curr = st.pop();
                if(curr.right != null){
                    temp = curr.right;
                    while(temp != null){
                        st.push(temp);
                        temp = temp.left;
                    }
                }
                k--;
            }
            
            return curr.val;
        }
    }

Log in to reply
 

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