[LeetCode] 783. 二叉搜索樹結點最小距離

1 題目描述

給定一個二叉搜索樹的根結點 root, 返回樹中任意兩節點的差的最小值。

示例:

輸入: root = [4,2,6,1,3,null,null]
輸出: 1
解釋:
注意,root是樹結點對象(TreeNode object),而不是數組。

給定的樹 [4,2,6,1,3,null,null] 可表示爲下圖:

在這裏插入圖片描述

最小的差值是 1, 它是節點1和節點2的差值, 也是節點3和節點2的差值。
注意:

二叉樹的大小範圍在 2 到 100。
二叉樹總是有效的,每個節點的值都是整數,且不重複。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

2 解題思路

看到二叉搜索樹的題目,馬上要想起來一條關鍵性質:

二叉搜索樹的中序遍歷是升序數組。

比如對於樣例輸入 root = [4,2,6,1,3,null,null],中序遍歷的結果就是 [1, 2, 3, 4, 6]。

題目要求兩個結點的最小距離,就是要求中序遍歷數組裏相鄰兩個元素差的最小值。
所以說:
1.中序遍歷二叉搜索樹得到的是有序結點;
2.定義一個輔助結點temp,用於存放上一個節點,當pre不爲空即從第二個節點開始記錄二叉搜索樹中兩個節點差值的最小值即可;

3 解決代碼

  • java代碼
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    TreeNode pre;
    int min = Integer.MAX_VALUE;
    public int minDiffInBST(TreeNode root) {
        inorder(root);
        //void類型的返回語句,這個是第三步的返回值
        return min;    
    }
    public void inorder(TreeNode node){
        //第一步,確定終止條件
        if(node == null){
            return;
        }
        //第二步,搞清遞歸要做什麼
        inorder(node.left);
        if(pre != null){
            min = Math.min(min, node.val - pre.val);  //中序出來的結果是遞增的,所以只需要比較前後兩個節點的值即可
        }
        pre = node;
        inorder(node.right);
    }
}
  • python代碼
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        def inorder(node):
            if not node:
                return 
            
            inorder(node.left)
            self.res = min(self.res, node.val - self.pre)
            self.pre = node.val
            inorder(node.right)
            
        self.pre = -9999
        self.res = 9999
        inorder(root)
        return self.res
發佈了242 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章