代码随想录算法训练营第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);
    }
};
相关推荐
北冥湖畔的燕雀5 小时前
C++泛型编程(函数模板以及类模板)
开发语言·c++
Larry_Yanan9 小时前
QML学习笔记(四十二)QML的MessageDialog
c++·笔记·qt·学习·ui
R-G-B9 小时前
【35】MFC入门到精通——MFC运行 不显示对话框 MFC界面不显示
c++·mfc·mfc运行 不显界面·mfc界面不显示
Madison-No710 小时前
【C++】探秘vector的底层实现
java·c++·算法
晚风残10 小时前
【C++ Primer】第十二章:动态内存管理
开发语言·c++·c++ primer
liu****10 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
保持低旋律节奏10 小时前
C++ stack、queue栈和队列的使用——附加算法题
c++
初圣魔门首席弟子10 小时前
【C++ 学习】单词统计器:从 “代码乱炖” 到 “清晰可品” 的复习笔记
开发语言·c++
十五年专注C++开发10 小时前
CFF Explorer: 一款Windows PE 文件分析的好工具
c++·windows·microsoft
郝学胜-神的一滴11 小时前
计算机图形学中的光照模型:从基础到现代技术
开发语言·c++·程序人生·图形渲染