[Leetcode 60 days with brush] day21 binary tree - 530. The minimum absolute difference of the binary search tree, 501. The mode in the binary search tree, 236. The nearest common ancestor of the binary tree


topic:

530. Minimum Absolute Difference for Binary Search Trees

Given the root node of a binary search tree  root , return  the minimum difference between any two different node values ​​in the tree  .

Difference is a positive number whose value is equal to the absolute value of the difference between the two values.

Example 1:

Input: root = [4,2,6,1,3]
 Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]
 Output: 1

hint:

  • The number of nodes in the tree ranges from [2, 104]
  • 0 <= Node.val <= 105


Thinking process and knowledge points: 

Then the binary search tree uses in-order traversal, which is actually an ordered array.

Finding the minimum difference between two numbers on an ordered array, is this a sub-question?

The most intuitive idea is to convert the binary search tree into an ordered array, and then traverse the array once to calculate the minimum difference.


 answer:

class Solution {
private:
vector<int> vec;
void traversal(TreeNode* root) {
    if (root == NULL) return;
    traversal(root->left);
    vec.push_back(root->val); // 将二叉搜索树转换为有序数组
    traversal(root->right);
}
public:
    int getMinimumDifference(TreeNode* root) {
        vec.clear();
        traversal(root);
        if (vec.size() < 2) return 0;
        int result = INT_MAX;
        for (int i = 1; i < vec.size(); i++) { // 统计有序数组的最小差值
            result = min(result, vec[i] - vec[i-1]);
        }
        return result;
    }
};

topic:

501. Modes in Binary Search Trees

Given the root of a binary search tree (BST) with duplicate values  , find and return all modes (ie, elements that occur most frequently) root in the BST  .

If there is more than one mode in the tree, it can be returned in  any order  .

Assume that BST satisfies the following definition:

  • The value of the node contained in the left subtree of the node  is less than or equal to  the value of the current node
  • The value of the node contained in the right subtree of the node  is greater than or equal to  the value of the current node
  • Both left and right subtrees are binary search trees

Example 1:

Input: root = [1,null,2,2]
 Output: [2]

Example 2:

Input: root = [0]
 Output: [0]

hint:

  • The number of nodes in the tree is in the  [1, 104] range
  • -105 <= Node.val <= 105

Thinking process and knowledge points: 

This tree has been traversed, and the frequency is counted with map

It doesn't matter which traversal you use in front, middle, and back order, because you just want to traverse it all, any traversal method will do, and there is nothing wrong with layer-order traversal!

Sort the statistics of the frequency of occurrence (that is, the value in the map)

Some students may want to sort the values ​​in the map directly, but they really can't. If you use std::map or std::multimap in C++, you can sort the keys, but you can't sort the values.

Therefore, the map needs to be converted into an array, that is, a vector, and then sorted. Of course, the type of data is also placed in the vector pair<int, int>. The first int is the element, and the second int is the frequency of occurrence.

Take the previous high-frequency elements

At this time, the array vector already stores pairs sorted by frequency, so just take out the previous high-frequency elements.


 answer:

class Solution {
private:

void searchBST(TreeNode* cur, unordered_map<int, int>& map) { // 前序遍历
    if (cur == NULL) return ;
    map[cur->val]++; // 统计元素频率
    searchBST(cur->left, map);
    searchBST(cur->right, map);
    return ;
}
bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
    return a.second > b.second;
}
public:
    vector<int> findMode(TreeNode* root) {
        unordered_map<int, int> map; // key:元素,value:出现频率
        vector<int> result;
        if (root == NULL) return result;
        searchBST(root, map);
        vector<pair<int, int>> vec(map.begin(), map.end());
        sort(vec.begin(), vec.end(), cmp); // 给频率排个序
        result.push_back(vec[0].first);
        for (int i = 1; i < vec.size(); i++) {
            // 取最高的放到result数组中
            if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
            else break;
        }
        return result;
    }
};

topic:

236. Nearest Common Ancestor of Binary Tree

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.

The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of a rooted tree T, the nearest common ancestor is expressed as a node x, satisfying that x is the ancestor of p and q and the depth of x is as large as possible ( a A node can also be its own ancestor )."

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
 Output: 3
 Explanation: Node 5 and node 1 's nearest common ancestor is node3 。

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
 Output: 5
 Explanation: The nearest common ancestor of node 5 and node 4 is node 5 。because By definition the nearest common ancestor node can be the node itself.

Example 3:

Input: root = [1,2], p = 1, q = 2
 Output: 1

hint:

  • The number of nodes in the tree is  [2, 105] within range.
  • -109 <= Node.val <= 109
  • all  Node.val 互不相同 .
  • p != q
  • p and  q both exist in the given binary tree.

Thinking process and knowledge points: 

When the recursive function has a return value: If you want to search for an edge, when the return value of the recursive function is not empty, return immediately. If you search the entire tree, directly use a variable left and right to catch the return value. The left and right There is also a need for logic processing in postorder, that is, the logic of processing intermediate nodes in postorder traversal (also backtracking).


 answer:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == q || root == p || root == NULL) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left != NULL && right != NULL) return root;

        if (left == NULL && right != NULL) return right;
        else if (left != NULL && right == NULL) return left;
        else  { //  (left == NULL && right == NULL)
            return NULL;
        }

    }
};

 


Welcome to like, bookmark, comment, your encouragement is the biggest motivation for my creation! (๑╹◡╹)ノ"""

Copyright statement: This article is an original article of CSDN blogger "Dumengjiu", which follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: Dumengjiu's blog_CSDN blog-csdn domain blogger

Guess you like

Origin blog.csdn.net/weixin_53310927/article/details/131355735