题目
题解
- 递归,深度优先遍历
- 广度优先遍历
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// class Solution {
// public:
// TreeNode* invertTree(TreeNode* root) {
// if(!root)
// return root;
// queue<TreeNode*> que;
// que.push(root);
// while(!que.empty()){
// int len=que.size();
// for(int i=0;i<len;i++){
// auto node=que.front();
// que.pop();
// auto 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;
auto tmp=invertTree(root->left);
root->left=invertTree(root->right);
root->right=tmp;
// swap(invertTree(root->left),invertTree(root->right));
return root;
}
};