【算法与数据结构】530、LeetCode二叉搜索树的最小绝对差

文章目录

  • 一、题目
  • 二、解法
  • 三、完整代码

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。

一、题目

【算法与数据结构】530、LeetCode二叉搜索树的最小绝对差_第1张图片
【算法与数据结构】530、LeetCode二叉搜索树的最小绝对差_第2张图片
【算法与数据结构】530、LeetCode二叉搜索树的最小绝对差_第3张图片

二、解法

  思路分析:二叉搜索树的性质是左子树的所有节点键值小于中间节点键值,右子树的所有节点键值大于中间节点键值,且左子树和右子树也是二叉搜索树,于是我们得到二叉搜索树的中序遍历是单调递增的有序数组,那么一个有序数组两数之间绝对值最小的值一定是相邻节点的差值,那么我们只要计算出中序遍历数组相邻元素差值的最小值即可。关于二叉搜索树的性质可以看这篇文章:【算法与数据结构】98、LeetCode验证二叉搜索树。
  程序如下

class Solution {
public:
    void traversal_midOrder(TreeNode* cur, vector<int>& vec) {
        if (cur == NULL) return;
        traversal_midOrder(cur->left, vec);     // 左
        vec.push_back(cur->val);                // 中
        traversal_midOrder(cur->right, vec);    // 右
    }

    int getMinimumDifference(TreeNode* root) {
        if (root == NULL) return {};
        vector<int> v;
        traversal_midOrder(root, v);
        int minVal = v[1] - v[0];
        if (v.size() != 1) {
            for (int i = 1; i < v.size()-1; i++) {
                if (v[i+1] - v[i] < minVal) minVal = v[i + 1] - v[i];
            }
        }
        return minVal;
    }
};

三、完整代码

# include 
# include 
# include 
# include 
using namespace std;

// 树节点定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    void traversal_midOrder(TreeNode* cur, vector<int>& vec) {
        if (cur == NULL) return;
        traversal_midOrder(cur->left, vec);     // 左
        vec.push_back(cur->val);                // 中
        traversal_midOrder(cur->right, vec);    // 右
    }

    int getMinimumDifference(TreeNode* root) {
        if (root == NULL) return {};
        vector<int> v;
        traversal_midOrder(root, v);
        int minVal = v[1] - v[0];
        if (v.size() != 1) {
            for (int i = 1; i < v.size()-1; i++) {
                if (v[i+1] - v[i] < minVal) minVal = v[i + 1] - v[i];
            }
        }
        return minVal;
    }
};

// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
    if (!t.size() || t[0] == "NULL") return;    // 退出条件
    else {
        node = new TreeNode(stoi(t[0].c_str()));    // 中
        if (t.size()) {
            t.assign(t.begin() + 1, t.end());
            Tree_Generator(t, node->left);              // 左
        }
        if (t.size()) {
            t.assign(t.begin() + 1, t.end());
            Tree_Generator(t, node->right);             // 右
        }
    }
}

template<typename T>
void my_print(T& v, const string msg)
{
    cout << msg << endl;
    for (class T::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << ' ';
    }
    cout << endl;
}

template<class T1, class T2>
void my_print2(T1& v, const string str) {
    cout << str << endl;
    for (class T1::iterator vit = v.begin(); vit < v.end(); ++vit) {
        for (class T2::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
            cout << *it << ' ';
        }
        cout << endl;
    }
}

// 层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
    queue<TreeNode*> que;
    if (root != NULL) que.push(root);
    vector<vector<int>> result;
    while (!que.empty()) {
        int size = que.size();  // size必须固定, que.size()是不断变化的
        vector<int> vec;
        for (int i = 0; i < size; ++i) {
            TreeNode* node = que.front();
            que.pop();
            vec.push_back(node->val);
            if (node->left) que.push(node->left);
            if (node->right) que.push(node->right);
        }
        result.push_back(vec);
    }
    return result;
}

int main()
{
    vector<string> t = { "4", "2", "1", "NULL", "NULL", "3", "NULL", "NULL", "6", "NULL", "NULL" };   // 前序遍历
    my_print(t, "目标树");
    TreeNode* root = new TreeNode();
    Tree_Generator(t, root);
    vector<vector<int>> tree = levelOrder(root);
    my_print2<vector<vector<int>>, vector<int>>(tree, "目标树:");

    Solution s;
    int result = s.getMinimumDifference(root);
    cout << "任意两节点之差的最小绝对值为:" << result << endl;

    system("pause");
    return 0;
}

end

你可能感兴趣的:(算法,算法)