当前位置:网站首页>427- binary tree (617. merge binary tree, 700. search in binary search tree, 98. verify binary search tree, 530. minimum absolute difference of binary search tree)

427- binary tree (617. merge binary tree, 700. search in binary search tree, 98. verify binary search tree, 530. minimum absolute difference of binary search tree)

2022-06-27 06:01:00 liufeng2023

617. Merge binary tree

 Insert picture description here

class Solution {
    
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
    
        if (root1 == nullptr)    return root2;
        if (root2 == nullptr)    return root1;

        root1->val += root2->val;

        root1->left = mergeTrees(root1->left, root2->left);
        root1->right = mergeTrees(root1->right, root2->right);
        return root1;
    }
};

 Insert picture description here

700. Search in binary search tree

 Insert picture description here

class Solution {
    
public:
    TreeNode* searchBST(TreeNode* root, int val) {
    
        if (root == nullptr || root->val == val) return root;

        if (root->val > val) return searchBST(root->left, val);
        if (root->val < val) return searchBST(root->right, val);

        return nullptr;
    }
};

 Insert picture description here

98. Verify binary search tree

 Insert picture description here

class Solution {
    
private:
    vector<int> res;

    void traversal(TreeNode* root)
    {
    
        if (root == nullptr)    return;

        traversal(root->left);
        res.push_back(root->val);
        traversal(root->right);
    }
public:
    bool isValidBST(TreeNode* root) {
    
        res.clear();
        traversal(root);


        for (int i = 1; i < res.size(); i++)
        {
    
            if (res[i - 1] < res[i])
            {
    
                continue;
            }
            else
            {
    
                return false;
            }
        }
        return true;
    }
};

 Insert picture description here

530. The minimum absolute difference of binary search tree

 Insert picture description here

class Solution {
    
private:
    vector<int> res;

    void traversal(TreeNode* root)
    {
    
        if (root == nullptr) return;

        traversal(root->left);
        res.push_back(root->val);
        traversal(root->right);
    }
public:
    int getMinimumDifference(TreeNode* root) {
    
        res.clear();
        traversal(root);
        if (res.size() < 2)  return 0;
        int result = INT_MAX;
        for (int i = 1; i < res.size(); i++)
        {
    
            result = std::min(result, res[i] - res[i - 1]);
        }

        return result;
    }
};

 Insert picture description here

原网站

版权声明
本文为[liufeng2023]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270558571949.html