783. 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.

 

Approach #1: C++.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDiffInBST(TreeNode* root) {
        solve(root);
        
        sort(nodes.begin(), nodes.end());
        
        int minNum = INT_MAX;
        
        for (int i = 1; i < nodes.size(); ++i) {
            minNum = min(minNum, nodes[i]-nodes[i-1]);
        }
        
        return minNum;
    }
    
    void solve(TreeNode* root) {
        if (root->left != NULL)
            minDiffInBST(root->left);
        
        nodes.push_back(root->val);
        
        if (root->right != NULL)
            minDiffInBST(root->right);
    }
    
    
private:
    vector<int> nodes;
};

  

Approach #2: Java. [Inorder travel]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Integer minDiff = Integer.MAX_VALUE, pre = null;
    public int minDiffInBST(TreeNode root) {
        if (root.left != null) minDiffInBST(root.left);
        if (pre != null) minDiff = Math.min(minDiff, root.val-pre);
        pre = root.val;
        if (root.right != null) minDiffInBST(root.right);
        return minDiff;
    }
}

  

Approach #3: Python.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    minDiff = float('inf')
    pre = -float('inf')
    
    def minDiffInBST(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root.left != None:
            self.minDiffInBST(root.left)
        self.minDiff = min(self.minDiff, root.val-self.pre)
        self.pre = root.val
        if root.right != None:
            self.minDiffInBST(root.right)
        
        return self.minDiff;
        

  

Notes:

The Inf and NaN in python.

 

posted @ 2018-12-04 11:59  Veritas_des_Liberty  阅读(250)  评论(0编辑  收藏  举报