LeetCode DAY18(530. Minimum Absolute Difference in BST&501. Find Mode in Binary Search Tree&236)

Preface

This is a new day to continue my binary tree journey.
Learn something new and keep reviewing what I learnt before.

1. Minimum Absolute Difference in BST

LeetCode Link: 530. Minimum Absolute Difference in BST
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

/**
 * Definition for a binary tree node.
 * 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 {
private:
vector<int> vec;//build a new array to store nodes
void traversal(TreeNode* root) {//recursion tree
    if (root == NULL) return;//remove case0
    traversal(root->left);//recursion left tree
    vec.push_back(root->val); // convert the tree to ordered array
    traversal(root->right);//recursion right tree
}
public:
    int getMinimumDifference(TreeNode* root) {//main function 
        vec.clear();//clear array
        traversal(root);//recursion root node
        if (vec.size() < 2) return 0;//remove case0, without minimumdifference with only one element
        int result = INT_MAX;//initial the result
        for (int i = 1; i < vec.size(); i++) { // count the minimumdifference in the array
            result = min(result, vec[i] - vec[i-1]);//give the minValue
        }
        return result;
    }
};

2. Find Mode in Binary Search Tree

LeetCode Link: 501. Find Mode in Binary Search Tree
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.

Analysis and Solution

Recursion And Backtrack

LeetCode C++ as followings Recursion And Backtrack

/**
 * Definition for a binary tree node.
 * 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 {
private:
    int maxCount = 0; // maxFrequency
    int count = 0; // count frequency
    TreeNode* pre = NULL;//initialize pre pointer points to first element
    vector<int> result;
    void searchBST(TreeNode* cur) {//inorder traverse
        if (cur == NULL) return ;//remove case0

        searchBST(cur->left);       // left recursion
                                    // middle 
        if (pre == NULL) { // first element
            count = 1;
        } else if (pre->val == cur->val) { // same as last element
            count++;//
        } else { // different with last element
            count = 1;
        }
        pre = cur; // update last element

        if (count == maxCount) { // put it into result if same with maxValue
            result.push_back(cur->val);
        }

        if (count > maxCount) { // if counter > maxFrequency
            maxCount = count;   // update maxFrequency
            result.clear();     // clear the result; outdated elements
            result.push_back(cur->val);
        }

        searchBST(cur->right);      // right recursion
        return ;
    }

public:
    vector<int> findMode(TreeNode* root) {
        count = 0;//initialization
        maxCount = 0;//initialization
        TreeNode* pre = NULL; //record last node
        result.clear();

        searchBST(root);
        return result;
    }
};

3. Lowest Common Ancestor of a Binary Tree

LeetCode Link: 236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

/**
 * 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {//root and target p q as parameters
        if (root == q || root == p || root == NULL) return root;//remove case0
        TreeNode* left = lowestCommonAncestor(root->left, p, q);//recursion left tree
        TreeNode* right = lowestCommonAncestor(root->right, p, q);//recursion right tree
        if (left != NULL && right != NULL) return root;//root is it's root node

        if (left == NULL && right != NULL) return right;//root node was returned by right 
        else if (left != NULL && right == NULL) return left;//root node was returned by left
        else  { //  (left == NULL && right == NULL)
            return NULL;
        }

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值