102.层序遍历 (BFS)
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> res;
//vector<int> path;//这个应该写在while循环里面,不然path中的元素会一直累加
if(root==NULL) return res;
que.push(root);
while(!que.empty()){
vector<int> path;//需要每次循环更新为空数组
int size=que.size();//要先记录下本层的元素个数
while(size--){
TreeNode* node=que.front();
que.pop();
path.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
res.push_back(path);
}
return res;
}
};
错因:vector<int>path应该定义在while循环内,每次循环更新记录当前层的数组为空数组,不然会一直累加。
226.翻转二叉树
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;
}
};
上面的写法是前序遍历,用后序也行,中序不行,会把左子树翻转到右边后继续翻转右子树(刚刚已经处理过了,原来的右子树没有翻转)
101.对称二叉树
本质上是判断根节点的左右子树是否可以相互翻转,需要收集底部左右孩子的信息返回给上一层。
所以只能用后序。(除了主函数之外需要额外写一个函数)
class Solution {
public:
bool compare(TreeNode* l,TreeNode* r){
if(l!=NULL&&r==NULL) return false;
else if(l==NULL&&r!=NULL) return false;
else if(l==NULL&&r==NULL) return true;
else if(l->val!=r->val) return false;
else{
bool outside=compare(l->left,r->right);
bool inside=compare(l->right,r->left);
return outside&&inside;
}
}
bool isSymmetric(TreeNode* root) {
return compare(root->left,root->right);
}
};