代码随想录day16

搜索,双指针,采取两个指针遍历,采用前中右

class Solution {
private:
int result = INT_MAX;
TreeNode* pre = NULL;
void traversal(TreeNode* cur) {
    if (cur == NULL) return;
    traversal(cur->left);   // 左
    if (pre != NULL){       // 中
        result = min(result, cur->val - pre->val);
    }
    pre = cur; // 记录前一个
    traversal(cur->right);  // 右
}
public:
    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return result;
    }
};

二叉树搜索树,统计众数

依旧是前序遍历,采用双指针的办法,但是要注意相同的情况,要放在前面

/**
 * 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 {
public:
    TreeNode* pre=NULL;
    vector<int> res;
    int count=0;
    int maxcount=INT_MIN;
    void traversal(TreeNode* cur){
        if(cur==NULL) return;
        traversal(cur->left);
    
       //第一个元素
        if(pre==NULL)   {count=1;} 
        else if(pre->val==cur->val) {count++;}
        else {count=1;} 
        if(count==maxcount){
            res.push_back(cur->val);
         }
        if(count>maxcount){
            maxcount=count;
            res.clear();
            res.push_back(cur->val);
        }
       
         
        pre=cur;

        traversal(cur->right);

    }
    vector<int> findMode(TreeNode* root) {
        traversal(root);
        return res;
        
    }
};

二叉树公共祖先,回溯算法,采用后序遍历

/**
 * 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) {
        //回溯是后序遍历,左右中
        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 right;
        else if(left!=NULL&&right==NULL) return left;
        else if(left!=NULL&&right!=NULL) return root;
        else  {return NULL;}
        
    }
};
相关推荐
夏末秋也凉1 小时前
力扣-动态规划-70 爬楼梯
算法·leetcode·动态规划
大萌神Nagato1 小时前
蓝桥杯15届JavaB组6题
算法·蓝桥杯·深度优先
Swift社区2 小时前
【Swift 算法实战】利用 KMP 算法高效求解最短回文串
vue.js·算法·leetcode
萌の鱼2 小时前
leetcode 73. 矩阵置零
数据结构·c++·算法·leetcode·矩阵
好看资源平台2 小时前
‌KNN算法优化实战分享——基于空间数据结构的工业级实战指南
数据结构·算法
AllYoung_3622 小时前
WebUI 部署 Ollama 可视化对话界面
人工智能·深度学习·算法·语言模型·aigc·llama
孤独得猿2 小时前
贪心算法精品题
算法·贪心算法
姜西西_2 小时前
合并区间 ---- 贪心算法
算法·贪心算法
不平衡的叉叉树2 小时前
使用优化版的编辑距离算法替代ES默认的评分算法
java·算法
黑色的山岗在沉睡3 小时前
P1038 [NOIP 2003 提高组] 神经网络
算法