1. 程式人生 > >二叉搜尋樹BST結點的最小距離

二叉搜尋樹BST結點的最小距離

原問題:輸入一個BST的根節點,返回該樹任意兩結點間差值的最小值。

我的程式碼(C++)

class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int const MAX_SIZE=100;
        int array[MAX_SIZE];
        int length=0;
        inOrderTraverse(root,array,length);
        return minDisOfArray(array,length);
    }
    void inOrderTraverse(TreeNode* root,int* array,int& length){
        if(root!=NULL){
            inOrderTraverse(root->left,array,length);
            length++;
            array[length-1]=root->val;
            inOrderTraverse(root->right,array,length);
        }
    }
    int minDisOfArray(int* a,int length){
        int minDis,curDis;
        minDis=a[length-1]-a[length-2];
        while(length-1){
            curDis=a[length-1]-a[length-2];
            minDis=curDis<minDis?curDis:minDis;
            length--;
        }
        return minDis;
    }

};

參考程式碼

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

差距:參考程式碼在中序遍歷的同時進行了最小值的計算。因為中序遍歷BST本身就已經嚴格使訪問的結點值按小到大嚴格排列,用全域性變數pre儲存上一個訪問到的值,root->val-pre計算兩相鄰大小結點的差值,並更新res。

另外注意臨界情況,即葉結點。

最大值與最小值的定義例子:

#define INT_MAX 2147483647

#define INT_MIN (-INT_MAX - 1)