代码随想录算法训练营第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);
    }
};
相关推荐
saltymilk3 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥3 小时前
C++ lambda 匿名函数
c++
沐怡旸9 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥10 小时前
C++ 内存管理
c++
博笙困了16 小时前
AcWing学习——双指针算法
c++·算法
感哥16 小时前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸1 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++