Friday, July 31, 2020

783. Minimum Distance Between BST Nodes

Q:

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.
  3. This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/

A:
第一遍,我是用vector save 再对比的
第二遍, 省掉了O(n) space.  只用2个变量代表前一个数和最终结果。  (同时我们不能假设preValue 是几,因此不能用其做flag.来表示是否已经找到left most.  当然更不能用minDiff. 因为就要改minDiff的值。因此多引入了一个变量findLeftMost )


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        int minDiff = INT_MAX;
        int preVal = INT_MAX;
        bool findLeftMost = false; // use extra flag, in case left most is the INT_MIN
        helper(root, preVal, minDiff, findLeftMost);
        return minDiff;
    }
private:
    void helper(TreeNode* root,  int & preVal, int & minDiff, bool & findLeftMost)
    {
        if(root==nullptr)
            return;
        
        helper(root->left, preVal, minDiff,findLeftMost);
        if(findLeftMost ) // if not the left-most node
        {
            minDiff = min(minDiff, root->val - preVal);
        }
        findLeftMost = true;
        preVal = root->val;
        helper(root->right, preVal, minDiff, findLeftMost);
    }
};



No comments:

Post a Comment