zoukankan      html  css  js  c++  java
  • 530. Minimum Absolute Difference in BST

    Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

    Example:

    Input:
    
       1
        
         3
        /
       2
    
    Output:
    1
    
    Explanation:
    The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
    

    Note: There are at least two nodes in this BST.

    给一棵二叉搜索树,找到他的任意两个节点的差的最小值

    刚开始理解错了,误认为求两个相邻节点的差的

    对于树的便利,我还是不够熟练啊  

    /**
     * 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 prev = -1;
        int min = INT_MAX;
        void GetMinDeff(TreeNode *root){
            if(root == NULL)    return;
            
            GetMinDeff(root->left);
            int diff;
            if(prev == -1)
                prev = root->val;
            else{
                diff = fabs(root->val - prev);
                if(min > diff)
                    min = diff;
                prev = root->val;
            }
            GetMinDeff(root->right);
        }
        int getMinimumDifference(TreeNode* root) {
            GetMinDeff(root);
            return min;
            
        }
    };

    最小值

  • 相关阅读:
    PowerMockito
    java--树封装
    plugin--Lombok
    Mysql--sql
    Oracle--sql
    hive--分区表和分桶表
    hive支持的数据类型和存储格式
    HashMap
    golang 创建 tun 设备
    golang ctrie demo
  • 原文地址:https://www.cnblogs.com/hutonm/p/6530388.html
Copyright © 2011-2022 走看看