代码随想录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;}
        
    }
};
相关推荐
南境十里·墨染春水2 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
@insist1232 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试
一只齐刘海的猫7 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1118 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
IronMurphy9 小时前
【算法五十七】146. LRU 缓存
算法·缓存
凌波粒9 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle9 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂10 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠10 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法