[LeetCode] Minimum Distance Between BST Nodes 二叉搜索樹中結點的最小距離


 

Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

Example :

Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

          4
        /   \
      2      6
     / \    
    1   3  

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

Note:

  1. The size of the BST will be between 2 and 100.
  2. The BST is always valid, each node's value is an integer, and each node's value is different.

 

這道題跟之前那道Minimum Absolute Difference in BST沒有任何區別,解法完全可以共用,講解也可以參見之前的帖子,這里就簡略的說一下。第一種方法很直接,通過中序遍歷按順序從小到大將所有的結點值都存入到一個數組中,然后就遍歷這個數組,找相鄰的兩個的差值最小的返回即可,參見代碼如下:

 

解法一:

class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int res = INT_MAX;
        vector<int> v;
        helper(root, v);
        for (int i = 1; i < v.size(); ++i) {
            res = min(res, v[i] - v[i - 1]);
        }
        return res;
    }
    void helper(TreeNode* node, vector<int>& vals) {
        if (!node) return;
        helper(node->left, vals);
        vals.push_back(node->val);
        helper(node->right, vals);
    }
};

 

我們可以優化上面解法的空間復雜度,並不記錄所有的結點值,而是只記錄之前的結點值,然后做差值更新結果res即可。

 

解法二:

class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int res = INT_MAX, pre = -1;
        helper(root, pre, res);
        return res;
    }
    void helper(TreeNode* node, int& pre, int& res) {
        if (!node) return;
        helper(node->left, pre, res);
        if (pre != -1) res = min(res, node->val - pre);
        pre = node->val;
        helper(node->right, pre, res);
    }
};

 

其實我們也不必非要用中序遍歷不可,用先序遍歷同樣可以利用到BST的性質,我們帶兩個變量low和high來分別表示上下界,初始化為int的極值,然后我們在遞歸函數中,分別用上下界和當前節點值的絕對差來更新結果res,參見代碼如下:

 

解法三:

class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int res = INT_MAX;
        helper(root, INT_MIN, INT_MAX, res);
        return res;
    }
    void helper(TreeNode* node, int low, int high, int& res) {
        if (!node) return;
        if (low != INT_MIN) res = min(res, node->val - low);
        if (high != INT_MAX) res = min(res, high - node->val);
        helper(node->left, low, node->val, res);
        helper(node->right, node->val, high, res);
    }
};

 

下面這種方法是解法一的迭代的寫法,思路跟之前的解法沒有什么區別,參見代碼如下:

 

解法四:

class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int res = INT_MAX, pre = -1;
        stack<TreeNode*> st;
        TreeNode* p = root;
        while (!st.empty() || p) {
            if (p) {
                st.push(p);
                p = p->left;
            } else {
                p = st.top(); st.pop();
                if (pre != -1) res = min(res, p->val - pre);
                pre = p->val;
                p = p->right;
            }
        }
        return res;
    }
};

 

類似題目:

Minimum Absolute Difference in BST

Binary Tree Inorder Traversal

 

參考資料:

https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/

https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/114834/Inorder-Traversal-O(N)-time-Recursion-C++JavaPython

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM