代码随想录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 小时前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵
努力学习的小廉2 小时前
我爱学算法之—— BFS之最短路径问题
算法·宽度优先
高山上有一只小老虎3 小时前
构造A+B
java·算法
木头左3 小时前
缺失值插补策略比较线性回归vs.相邻填充在LSTM输入层的性能差异分析
算法·线性回归·lstm
sin_hielo3 小时前
leetcode 2435
数据结构·算法·leetcode
crescent_悦3 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
鳄鱼儿4 小时前
密码算法的OID查阅
算法
lxh01134 小时前
螺旋数组题解
前端·算法·js
czlczl200209255 小时前
算法:二叉树的公共祖先
算法
小白程序员成长日记6 小时前
2025.11.23 力扣每日一题
算法·leetcode·职场和发展