Beautiful Java solution using stack


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

Log in to reply
 

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