zoukankan      html  css  js  c++  java
  • LeetCode530. 二叉搜索树的最小绝对差

    因为是二叉搜索树,所以中序遍历可以得到一个升序序列。

    因此可以中序遍历这个二叉搜索树,把结果存在一个数组中,然后遍历这个数组,计算相邻值的最小值,这个最小值就是答案。

    /**
     * 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> nodes;
    
        void inOrder(TreeNode* root) {
            if(root == NULL) {
                return ;
            }
            inOrder(root -> left);
            nodes.push_back(root -> val);
            inOrder(root -> right);
        }
    
        int getMinimumDifference(TreeNode* root) {
            if(root == NULL) {
                return 0;
            }
            inOrder(root);
            int res = INT_MAX;
            for(int i = 0; i < nodes.size() - 1; ++i) {
                res = min(res, nodes[i + 1] - nodes[i]);
            }
            return res;
        }
    };
    
  • 相关阅读:
    解题报告:luogu P1156
    解题报告:AT3605
    矩阵乘法与斐波那契数列
    九、模块
    八、异常
    七、文件处理
    六、对象和内存分析
    五、函数和内存分析
    四、控制语句
    三、序列
  • 原文地址:https://www.cnblogs.com/linrj/p/13972945.html
Copyright © 2011-2022 走看看