代码随想录算法训练营第15天

层序遍历

思路:

注意:

代码:

cpp 复制代码
/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*>que;
        vector<vector<int>>res;
        if(root){ que.push(root);}
        while(!que.empty()){
            int size = que.size();
            vector<int>vec;
            for(int i=0; i<size; i++){
                
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }

            res.push_back(vec);

        }
        return res;
    }
};

226.翻转二叉树 (优先掌握递归)

思路:

复制代码
	确定  递归函数的参数 和  返回值  
	确定  循环终止条件                    if(root == nullptr) return root;
	确定单层递归遍历逻辑 (中, 左  右等等)
				        invertTree(root->left);
    				invertTree(root->right);
    				swap(root->left, root->right);

注意:左右中

代码:

cpp 复制代码
class Solution {
public:


    TreeNode* invertTree(TreeNode* root) {
        if(root == nullptr) return root;
        invertTree(root->left);
        invertTree(root->right);
        swap(root->left, root->right);
        return root;
    }
};

101. 对称二叉树 (优先掌握递归)

思路:

复制代码
	传入参数:
			left,  right  
	终止条件:
		判断 左为空  右不为空  false
		判断 左为非空  右为空  false
		判断 左为空  右为空  true
	单层递归逻辑:
		compair(left->left, right->right) && compair(left->right, right->left);

注意: 不能利用left->val == right->val 来判断 两棵树是 对称二叉树

代码:

cpp 复制代码
class Solution {
public:
bool compair(TreeNode* left, TreeNode*right){
    if(left == nullptr && right !=nullptr) return false;
    else if(left !=nullptr && right ==nullptr) return false;
    else if(left == nullptr && right == nullptr) return true;
    else if(left->val != right->val) return false;
    // else if(left->val == right->val) return true;
    
    return compair(left->left, right->right) && compair(left->right, right->left);
     
    


}
    bool isSymmetric(TreeNode* root) {
        if(root == nullptr) return true;
        return compair(root->left, root->right);
    }
};
相关推荐
上去我就QWER2 小时前
Qt快捷键“魔法师”:QKeySequence
开发语言·c++·qt
将编程培养成爱好5 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极5 小时前
设计模式学习(3)-行为型模式
c++·设计模式
随意起个昵称6 小时前
【递归】二进制字符串中的第K位
c++·算法
mjhcsp7 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
Mr_WangAndy8 小时前
C++_chapter15_C++重要知识点_lambda,initializer_list
c++·lambda·初始化列表
Maple_land8 小时前
第1篇:Linux工具复盘上篇:yum与vim
linux·运维·服务器·c++·centos
hggngx548h9 小时前
有哪些C++20特性可以在Dev-C++中使用?
开发语言·c++·c++20
计科土狗9 小时前
算法基础入门第一章
c++·算法
9ilk10 小时前
【仿RabbitMQ的发布订阅式消息队列】 ---- 功能测试联调
linux·服务器·c++·分布式·学习·rabbitmq