File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed
783. Minimum Distance Between BST Nodes .playground Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ import UIKit
2+ import UIKit
3+
4+ public class TreeNode {
5+ public var val : Int
6+ public var left : TreeNode ?
7+ public var right : TreeNode ?
8+ public init ( ) { self . val = 0 ; self . left = nil ; self . right = nil ; }
9+ public init ( _ val: Int ) { self . val = val; self . left = nil ; self . right = nil ; }
10+ public init ( _ val: Int , _ left: TreeNode ? , _ right: TreeNode ? ) {
11+ self . val = val
12+ self . left = left
13+ self . right = right
14+ }
15+ }
16+
17+ /**
18+ # Intuition
19+ Use inorder DFS since the answer will always the minimum difference between two adjacent nodes in ascending order.
20+
21+ # Approach
22+ Traverse the tree using DFS inorder traversal.
23+ Store the previous visited node.
24+ Find the difference between the current node and the previous node.
25+
26+ # Complexity
27+ - Time complexity:
28+ O(n) where `n` is `root.nodes.size`
29+
30+ - Space complexity:
31+ O(1) or O(h) where `h` is the height of the tree
32+ */
33+
34+ class Solution {
35+
36+ var prev : TreeNode ?
37+
38+ func evaluate( _ root: TreeNode ? , _ currMin: inout Int ) {
39+ guard let root = root else {
40+ return
41+ }
42+
43+ evaluate ( root. left, & currMin)
44+ if let prev = prev {
45+ print ( root. val, prev. val, root. val - prev. val)
46+ currMin = min ( currMin, root. val - prev. val)
47+ }
48+ prev = root
49+ evaluate ( root. right, & currMin)
50+ }
51+
52+ func minDiffInBST( _ root: TreeNode ? ) -> Int {
53+ var ans = Int . max
54+ evaluate ( root, & ans)
55+ return ans
56+ }
57+ }
Original file line number Diff line number Diff line change 1+ <?xml version =" 1.0" encoding =" UTF-8" standalone =" yes" ?>
2+ <playground version =' 5.0' target-platform =' ios' buildActiveScheme =' true' importAppTypes =' true' >
3+ <timeline fileName =' timeline.xctimeline' />
4+ </playground >
You can’t perform that action at this time.
0 commit comments