题目:二叉搜索树的最小绝对差

530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

思路:就是一个中序遍历的过程,使用双指针的方式来实现,和昨天最后一道题目相似

class Solution {
public:
    TreeNode* pre = nullptr;
    int min_nums = INT_MAX;
    void traversal(TreeNode* root)
    {
        if(root == nullptr)
        {
            return;
        }
        traversal(root->left);
        if(pre != nullptr)
        {
            int tmp = root->val - pre->val;
            if(tmp < min_nums)
            {
                min_nums = tmp;
            }
        }
        pre = root;
        traversal(root->right);
        return;
    }
    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return min_nums;
    }
};

题目:二叉搜索树中的众数

501. 二叉搜索树中的众数 - 力扣(LeetCode)

思路:考虑到二叉搜索树的特性可以采用中序遍历的方式来对二叉树来进行遍历

class Solution {
public:
    vector<int> result{0};
    int maxcount= 0;
    int count = 0;
    TreeNode* pre;
    void traversal(TreeNode* root)
    {
        if(root == nullptr)
        {
            return;
        }
        traversal(root->left);
        if(pre == nullptr)
        {
            count = 1;
        }
        else if(root->val == pre->val)
        {
            count ++;
        }
        else
        {
            count = 1;
        }
        pre = root;
​
        if(count == maxcount)
        {
            result.push_back(root->val);
        }
        if(count > maxcount)
        {
            maxcount = count;
            result.clear();
            result.push_back(root->val);
        }
        traversal(root->right);
​
    }
    vector<int> findMode(TreeNode* root) {
        traversal(root);
        return result;
    }
};

题目:二叉树的最近公共祖先

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

思路:采用后续的方式从左右子树分别搜索,若碰到所需节点就向上传回节点即可。(后续遍历,向上传递)

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