my stack dfs solution


  • 0
    public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<>();
            while(root != null) {
                while(root != null) {
                    stack.push(root);
                    root = root.left;
                }
                TreeNode c = stack.pop();
                k--;
                if(k == 0) return c.val;
                while(c.right == null) {
                    c = stack.pop();
                    k--;
                    if(k == 0) return c.val;
                }
                root = c.right;
            }
            return Integer.MIN_VALUE;
        }

Log in to reply
 

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