Java Iterative O(k) Solution


  • 0
    X
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> st = new Stack<TreeNode>();
            TreeNode cur = root;
            int n = 0;
            while(cur !=null || !st.empty()){
                while(cur != null){
                    st.push(cur);
                    cur = cur.left;
                }
                cur = st.pop();
                if(++n == k)    return cur.val;
                cur = cur.right;
            }
            return 0;
        }
    }

Log in to reply
 

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