"原文链接 [链接] Description: Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in .."

[每日 LeetCode] 783. Minimum Distance Between BST Nodes

原文链接 783. Minimum Distance Between BST Nodes

Description:

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.

思路:本题要求返回二叉搜索树两个结点间的最小距离。直接使用中序遍历,将结点依次保存在数组中,再从数组中找两个相邻的元素最小差值。


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) {
        vector<int> vec;
        dfs(root,vec);
        int res = INT_MAX;
        for(int i=1; i<vec.size(); i++){
            res = min(res, vec[i]-vec[i-1]);
        }
        return res;
    }
    void dfs(TreeNode* root, vector<int> & vec)
    {
        if(root == nullptr)    
            return ;
        dfs(root->left,vec);
        vec.push_back(root->val);
        dfs(root->right,vec);
    }
};

运行时间:4ms

运行内存:11.8M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    149 引用 • 35 回帖
  • Tree
    33 引用 • 5 回帖
  • Easy
    101 引用 • 10 回帖
回帖   
请输入回帖内容...