0530-二叉搜尋樹的最小絕對差
阿新 • • 發佈:2021-11-19
給你一個二叉搜尋樹的根節點 root ,返回 樹中任意兩不同節點值之間的最小差值 。
差值是一個正數,其數值等於兩值之差的絕對值。
示例 1:
輸入:root = [4,2,6,1,3]
輸出:1
示例 2:
輸入:root = [1,0,48,null,null,12,49]
輸出:1
提示:
樹中節點的數目範圍是 [2, 104]
0 <= Node.val <= 105
注意:本題與 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ 相同
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst
參考:
python
# 0530.二叉搜尋樹的最小絕對差 # 遞迴-中序-陣列比較 class Solution: def getMinimumDifference(self, root: *TreeNode) -> int: res = [] r = float("inf") def buildaList(root): # 把二叉搜尋樹轉換成有序陣列 if not root: return None if root.left: buildaList(root.left) # 左 res.append(root.val) # 中 if root.right: buildaList(root.right) # 右 return res buildaList(root) for i in range(len(res) - 1): # 統計有序陣列的最小差值 r = min(abs(res[i] - res[i + 1]), r) return r class Solution1: def getMinimumDifference(self, root: *TreeNode) -> int: result = 1<<63-1 pre = None def travel(node): nonlocal result, pre if not node: return travel(node.left) if pre != None: result = min(result, node.val-pre.val) pre = node # 記錄前一個 travel(node.right) travel(root) return result class Solution2: def getMinimumDifference(self, root: TreeNode) -> int: stack = [] cur = root pre = None result = 1<<63-1 while cur or stack: if cur: # 遍歷至最左左節點 stack.append(cur) cur = cur.left else: # 處理棧頂元素 cur = stack.pop() if pre: result = min(result, cur.val-pre.val) pre = cur cur = cur.right return result
golang
package binaryTree import "math" // 遞迴-中序-陣列比較 func getMinimumDifference1(root *TreeNode) int { res := []int{} var travel func(node *TreeNode) travel = func(node *TreeNode) { if node == nil { return } travel(node.Left) res = append(res, node.Val) travel(node.Right) } travel(root) if len(res) < 2 { return 0 } Min := math.MaxInt64 for i:=1;i<len(res);i++ { temp := res[i] - res[i-1] if Min > temp { Min = temp } } return Min } // 遞迴-中序前驅節點-利用BST的性質 func getMinimumDifference2(root *TreeNode) int { result := math.MaxInt64 var pre *TreeNode var travel func(node *TreeNode) travel = func(node *TreeNode) { if node == nil { return } travel(node.Left) if pre != nil { temp := node.Val - pre.Val if result > temp { result = temp } } pre = node travel(node.Right) } travel(root) return result } // 迭代-中序遍歷-有限變數處理 func getMinimumDifference3(root *TreeNode) int { stack := []*TreeNode{} cur := root var pre *TreeNode result := math.MaxInt64 for cur != nil || len(stack) > 0 { if cur != nil { stack = append(stack, cur) cur = cur.Left } else { cur = stack[len(stack)-1] stack = stack[:len(stack)-1] if pre != nil { temp := cur.Val - pre.Val if result > temp { result = temp } } pre = cur cur = cur.Right } } return result }