Elegant Iterative Java Solution 10 lines


  • 0
    J
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            int count = 0;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode p = root;
            while(!stack.isEmpty() || p != null){
                while(p != null){stack.push(p); p = p.left;}
                p = stack.pop();
                if(++count == k) return p.val; 
                p = p.right;
            }
            return -1;
        }

Log in to reply
 

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