102.二叉树的层序遍历(中等)
leetcode题目链接:102. 二叉树的层序遍历 - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)
视频讲解:讲透二叉树的层序遍历 | 广度优先搜索 | LeetCode:102.二叉树的层序遍历_哔哩哔哩_bilibili
题目描述:
解题思路:
用一个队列来存储节点,一个size来控制层次。
题目代码:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr)
return {};
TreeQueue.push(root);
TreeNode* cur;
int size = 1;
while (!TreeQueue.empty())
{
for (int i = 0; i < size; i++)
{
cur = TreeQueue.front();
tmp.push_back(cur->val);
TreeQueue.pop();
if (cur->left != nullptr)
TreeQueue.push(cur->left);
if (cur->right != nullptr)
TreeQueue.push(cur->right);
}
result.push_back(tmp);
tmp.clear();
size = TreeQueue.size();
}
return result;
}
private:
queue<TreeNode*> TreeQueue;
vector<vector<int>> result;
vector<int> tmp;
};
226.翻转二叉树(简单)
leetcode题目链接:226. 翻转二叉树 - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)
视频讲解:听说一位巨佬面Google被拒了,因为没写出翻转二叉树 | LeetCode:226.翻转二叉树_哔哩哔哩_bilibili
题目描述:
解题思路:
递归法,前序或者后序遍历,每次都交换左右节点。
题目代码:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr)
return nullptr;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
101. 对称二叉树(简单)
leetcode题目链接:101. 对称二叉树 - 力扣(LeetCode)
文章讲解:代码随想录 (programmercarl.com)
视频讲解:新学期要从学习二叉树开始! | LeetCode:101. 对称二叉树_哔哩哔哩_bilibili
题目描述:
解题思路:
采用二叉树的后序遍历,递归对比左子树的左孩子与右子树的有孩子(外侧),左子树的右孩子和右子树的左孩子(内存)。
题目代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root->left == nullptr && root->right == nullptr)
return true;
return compare(root->left, root->right);
}
private:
bool compare(TreeNode* left, TreeNode* right)
{
if (left == nullptr && right != nullptr) return false;
if (left != nullptr && right == nullptr) return false;
if (left != nullptr && right != nullptr && left->val != right->val)return false;
if (left == nullptr && right == nullptr) return true;
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
return outside && inside;
}
};