Just inorder travel the tree.
Note: There are at least two nodes in this BST.
def getMinimumDifference(self, root): def dfs(node, l=): if node.left: dfs(node.left, l) l.append(node.val) if node.right: dfs(node.right, l) return l l = dfs(root) return min([abs(a-b) for a,b in zip(l, l[1:])])
If it's not a BST, just apply
l = sorted(bfs(root))
@ZhengwuFang If it is not BST, the order is random.
@lee215 sorted() makes this solution O(NlogN)
@albert_001 I didn't use sort in this solution. Sort is only used when it's not a BST
@lee215 Will level order traversal work?
I don't think so.
@algowl Agree. Edited.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.