zoukankan      html  css  js  c++  java
  • [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.

    找出BST中两个节点的最小值。

    1、利用中序遍历将书中节点值按顺序放入数组中。

    2、找出数组中相邻元素间差的绝对值的最小值即可。

    /**
     * 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:
        vector<int> inVec;
        int minDiffInBST(TreeNode* root) {
            inOrder(root);
            int res = INT_MAX;
            for (int i = 1; i < inVec.size(); i++) {
                res = min(res, abs(inVec[i] - inVec[i - 1]));
            }
            return res;
        }
        
        void inOrder(TreeNode* root) {
            if (root == nullptr)
                return;
            inOrder(root->left);
            inVec.push_back(root->val);
            inOrder(root->right);
        }
    };
    // 6 ms
  • 相关阅读:
    APP支付,后台支付宝生成预支付设置超时时间timeout_express无效,使用time_expire代替
    一些学习资料
    自连接
    模型成员
    模型查询
    模板
    管理站点
    视图
    设计模型
    搭建开发环境
  • 原文地址:https://www.cnblogs.com/immjc/p/8441207.html
Copyright © 2011-2022 走看看