层序遍历的递归写法很妙
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
Sequencetraversal(root,res,0);
return res;
}
private:
void Sequencetraversal(TreeNode* root,
vector<vector<int>> &res,int depth){
if(root==nullptr) return;
if(depth==res.size()) res.push_back(vector<int>());
res[depth].push_back(root->val);
Sequencetraversal(root->left,res,depth+1);
Sequencetraversal(root->right,res,depth+1);
}
};
226.翻转二叉树可以用层序遍历的迭代写法,或者递归,注意递归不能写成中序
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if(root) que.push(root);
while(!que.empty()){
int size=que.size();
for(int i=0;i<size;++i){
TreeNode* cur=que.front();
que.pop();
swap(cur->left,cur->right);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
return root;
}
};
101对称二叉树,这个递归写法非常有学习价值
class Solution {
public:
bool compareLAR(TreeNode* leftnode,TreeNode* rightnode){
if(leftnode!=nullptr && rightnode==nullptr) return false;
else if(leftnode==nullptr && rightnode!=nullptr) return false;
else if(leftnode==nullptr && rightnode==nullptr) return true;
else if(leftnode->val!=rightnode->val) return false;
bool outBool=compareLAR(leftnode->left,rightnode->right);
bool inBool=compareLAR(leftnode->right,rightnode->left);
return outBool&&inBool;
}
bool isSymmetric(TreeNode* root) {
if(root==nullptr) return root;
bool res=compareLAR(root->left,root->right);
return res;
}
};