第一题: 层序遍历
层序遍历这种类型的题目有类似的解法,可以利用队列这种数据结构进行解答,因为队列具有先进先出的特点,可以利用这一特性将每一层的数据一起遍历。
层序遍历的代码如下,需要注意的是size记录了每一层元素的个数:
①迭代法:
//迭代法
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
while(size--) {
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);
}
result.push_back(vec);
}
return result;
}
};
②递归法:
//递归法
class Solution {
public:
void order(TreeNode* cur, vector<vector<int>>& result, int depth)
{
if (cur == nullptr) return;
if (result.size() == depth) result.push_back(vector<int>());
result[depth].push_back(cur->val);
order(cur->left, result, depth + 1);
order(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
int depth = 0;
order(root, result, depth);
return result;
}
};
第二题: 226.翻转二叉树 (优先掌握递归)
这道题可以采用递归解法,也可以采用迭代的解法,优先掌握递归解法。这道题的思路是:对整个二叉树进行层序遍历,并且交换每个结点的左子节点和右子节点,给出代码:
①层序遍历法:
//层序遍历法
//层序遍历,每次交换每个节点的左子节点和右子节点
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if(root)
que.push(root);
while(!que.empty()) {
int size = que.size();
auto node = que.front();
que.pop();
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
return root;
}
};
②递归法:
//递归法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root)
return root;
swap(root->left, root->right); // 中
invertTree(root->left); // 左
invertTree(root->right); // 右
return root;
}
};
第三题: 101. 对称二叉树 (优先掌握递归)
这道题可以用递归的方法解决,并且需要使用后序遍历的方法,准确的来说是一个树的遍历顺序是左右中,另一个树的遍历顺序是右左中。代码如下:
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right) {
if(!left && !right)
return true;
else if(!left && right)
return false;
else if(left && !right)
return false;
else if(left->val != right->val)
return false;
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
return outside && inside;
}
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return compare(root->left, root->right);
}
};
Day15打卡!!!