102.二叉树的层序遍历
题目内容:给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
我的代码:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> que;
if(!root) {
return result;
}
if(root) {
que.push(root);
}
while(!que.empty()) {
int size = que.size();
vector<int> temp;
while(size--) {
TreeNode* node = que.front();
que.pop();
if(node) {
temp.push_back(node -> val);
}
if(node -> left) {
que.push(node -> left);
}
if(node -> right) {
que.push(node -> right);
}
}
result.push_back(temp);
temp.clear();
}
return result;
}
};
反思:层序遍历使用队列,根结点入队,读取队列元素个数size,size也就是要出队并存储数据的的元素个数,注意需要赋值后单用而不直接使用que.size(),因为循环过程中que.size()在不断变化;根据确定的循环次数,每次循环让队首出队,存储数据,再让根结点的左右孩子入队;直到队为空,说明结点都遍历完了且没有结点再入队了。
226.翻转二叉树
题目内容:给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
我的代码(递归):
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
swap_tree(root);
return root;
}
void swap_tree(TreeNode* root) {
if(root == nullptr) return;
swap(root -> left, root -> right);
swap_tree(root -> left);
swap_tree(root -> right);
}
};
反思:递归终止条件就是遍历到了空结点,此时返回;每一层递归的操作就是交换左右孩子,这里使用了先序遍历,“中”处理完后处理左孩子、右孩子。
101.对称二叉树
题目内容:给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
我的代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr || (root -> left == nullptr && root -> right == nullptr)) return true;
return check(root -> left, root -> right);
}
bool check(TreeNode* left, TreeNode* right) {
if((left == nullptr && right != nullptr) || (left != nullptr && right == nullptr)) return false;
if(left == nullptr && right == nullptr) return true;
if(left -> val != right -> val) return false;
bool outside = check(left -> left, right -> right);
bool inside = check(left -> right, right -> left);
return outside && inside;
}
};
反思:本道题采用递归后序遍历法,左右孩子分情况讨论:
1.左右孩子一个为空,返回false;
2.左右孩子都为空,返回true;
3.左右孩子值不等,返回false;
4.左右孩子都不为空且值相等,进行下一次遍历;
这道题采用先比较外侧再比较内侧的方法,进行递归。