Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Elena Feoktistova
Java O(1) space only one traversal

Elena Feoktistova

Dec 25, 2023

public class Solution { public int minDiffInBST(TreeNode root) { int minDiff = Integer.MAX_VALUE; TreeNode prev = null; Stack<TreeNode> stack = new Stack<>(); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); if (prev != null) { minDiff = Math.min(curr.val - prev.val, minDiff); } prev = curr; curr = curr.right; } return minDiff; } }

0

0

Comments
Comments
J
Jimmy 2 years ago

A recursive O(1) space solution in C++:

#include <iostream> #include <vector> #include <algorithm> #include <climits> // TreeNode structure to represent the Binary Search Tree nodes. // struct TreeNode { // int val; // TreeNode* left; // TreeNode* r...
Pavel Kostenko
Pavel Kostenko10 months ago

I'm not even sure this one is O(1). Even though you're using an interative approach and not utilizing recursive stack. You have internal stack variable, with can grow to O(n) in the worst case with unbalanced tree (one long branch to the left). If tree is balanced it ca...

On this page