第15天,坚持!
以下题目皆在Carl老师的 代码随想录 中(页面左边有对应题目的目录)有详细讲解,这是博主学习的心得和日志,感兴趣的建议去阅读一下原文。
复习和巩固区域变量的基础
/**
* 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;
// 把树的根节点推入队列
if (root != nullptr) que.push(root);
// 弄个二维数组,因为输出的结果中包含每层的数组
vector<vector<int>> res;
// 巩固基础知识:function/loop里创建的variable是local variable,随着function return销毁/重置
// loop里的local variables随着每loop结束被销毁和重置
while(!que.empty()){
//当前层的长度, 每loop重置
int size = que.size();
//用来储存当前层的元素代表当层数组,每loop重置
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);
}
//把本层的size--处理完填入vec放到二维数组中
res.push_back(vec);
}
return res;
}
};
/**
* 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* invertTree(TreeNode* root) {
if(root == nullptr) return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
/**
* 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:
bool compare(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;
//现在所剩的左右节点就是不为空且数值相等的节点了
//做递归,做下一层的判断
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
//同时判断两边,相等则对称
bool isSame = outside && inside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr) return true;
return compare(root->left, root->right);
}
};