代码随想录算法训练营第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);
    }
};
相关推荐
芒果披萨6 分钟前
日志管理 logging
java·开发语言·c++
天若有情6731 小时前
颠覆C++传统玩法!Property属性与伪类,开辟静态语言新维度
java·c++·servlet
CylMK1 小时前
题解:P11625 [迷宫寻路 Round 3] 迷宫寻路大赛
c++·数学·算法
计算机安禾1 小时前
【数据结构与算法】第44篇:堆(Heap)的实现
c语言·开发语言·数据结构·c++·算法·排序算法·图论
tankeven1 小时前
HJ175 小红的整数配对
c++·算法
ShineWinsu1 小时前
对于Linux:“一切皆文件“以及缓冲区的解析
linux·运维·c++·面试·笔试·缓冲区·一切皆文件
沈跃泉2 小时前
C++串口类实现
c++·windows·串口通信·串口类
智者知已应修善业2 小时前
【51单片机非精准计时2个外部中断启停】2023-5-29
c++·经验分享·笔记·算法·51单片机
沐雪轻挽萤2 小时前
3. C++17新特性-带初始化的 if 和 switch 语句
开发语言·c++
Magic--3 小时前
C++ 智能指针
开发语言·c++·算法