The minimum pairwise difference on a general tree needs all pairs. In a BST, inorder is sorted, so the minimum lies between adjacent values.
Walk inorder, keep the predecessor, and update with val - pre. Seed pre at \(-\infty\) so the first node is skipped. One inorder pass suffices.
The problem requires us to find the minimum difference between the values of any two nodes. Since the inorder traversal of a binary search tree is an increasing sequence, we only need to find the minimum difference between the values of two adjacent nodes in the inorder traversal.
We can use a recursive method to implement the inorder traversal. During the process, we use a variable \(\textit{pre}\) to save the value of the previous node. This way, we can calculate the minimum difference between the values of two adjacent nodes during the traversal.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary search tree.
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defgetMinimumDifference(self,root:Optional[TreeNode])->int:defdfs(root:Optional[TreeNode]):ifrootisNone:returndfs(root.left)nonlocalpre,ansans=min(ans,root.val-pre)pre=root.valdfs(root.right)pre=-infans=infdfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcgetMinimumDifference(root*TreeNode)int{constinfint=1<<30ans,pre:=inf,-infvardfsfunc(*TreeNode)dfs=func(root*TreeNode){ifroot==nil{return}dfs(root.Left)ans=min(ans,root.Val-pre)pre=root.Valdfs(root.Right)}dfs(root)returnans}
The minimum pairwise difference on a general tree needs all pairs. In a BST, inorder is sorted, so the minimum lies between adjacent values. Recursing inorder and subtracting the predecessor is correct on a short tree.
The tree can contain \(10^4\) nodes. A left chain makes this walk recurse once per node and overflow the call stack.
Each node only needs the previous value. The walk does not need a return value, as long as the left subtree is finished before the node and the right subtree comes after.
An explicit stack performs that inorder walk. On entry it pushes an exit marker and the left child; on exit it updates the answer with the current value minus the predecessor and pushes the right child. The predecessor starts at \(-\infty\), so the first node does not become the answer.
The minimum difference between any two node values of a binary search tree is the minimum gap between adjacent values in its increasing inorder sequence.
An explicit stack walks the tree in that order, and \(\textit{pre}\) stores the previous value, initially \(-\infty\). On entry we push an exit marker and the left child. On exit we update the answer with the current value minus \(\textit{pre}\), store the current value in \(\textit{pre}\), and push the right child.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the binary search tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defgetMinimumDifference(self,root:Optional[TreeNode])->int:pre=-infans=infstk=[(root,0)]whilestk:node,state=stk.pop()ifnodeisNone:continueifstate==0:stk.append((node,1))stk.append((node.left,0))continueans=min(ans,node.val-pre)pre=node.valstk.append((node.right,0))returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcgetMinimumDifference(root*TreeNode)int{constinfint=1<<30ans,pre:=inf,-inftypeframestruct{node*TreeNodestateint}stk:=[]frame{{root,0}}forlen(stk)>0{cur:=stk[len(stk)-1]stk=stk[:len(stk)-1]node,state:=cur.node,cur.stateifnode==nil{continue}ifstate==0{stk=append(stk,frame{node,1},frame{node.Left,0})continue}ans=min(ans,node.Val-pre)pre=node.Valstk=append(stk,frame{node.Right,0})}returnans}