Skip to content

Commit eff8833

Browse files
authored
Create minimum-distance-between-bst-nodes.py
1 parent dbaf36b commit eff8833

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Given a Binary Search Tree (BST) with the root node root,
5+
# return the minimum difference between the values of any two different nodes in the tree.
6+
#
7+
# Example :
8+
#
9+
# Input: root = [4,2,6,1,3,null,null]
10+
# Output: 1
11+
# Explanation:
12+
# Note that root is a TreeNode object, not an array.
13+
#
14+
# The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
15+
#
16+
# 4
17+
# / \
18+
# 2 6
19+
# / \
20+
# 1 3
21+
#
22+
# while the minimum difference in this tree is 1,
23+
# it occurs between node 1 and node 2, also between node 3 and node 2.
24+
#
25+
# Note:
26+
# - The size of the BST will be between 2 and 100.
27+
# - The BST is always valid, each node's value is an integer, and each node's value is different.
28+
29+
# Definition for a binary tree node.
30+
# class TreeNode(object):
31+
# def __init__(self, x):
32+
# self.val = x
33+
# self.left = None
34+
# self.right = None
35+
36+
class Solution(object):
37+
def minDiffInBST(self, root):
38+
"""
39+
:type root: TreeNode
40+
:rtype: int
41+
"""
42+
def dfs(node):
43+
if not node:
44+
return
45+
dfs(node.left)
46+
self.result = min(self.result, node.val-self.prev)
47+
self.prev = node.val
48+
dfs(node.right)
49+
50+
self.prev = float('-inf')
51+
self.result = float('inf')
52+
dfs(root)
53+
return self.result
54+

0 commit comments

Comments
 (0)