226.翻转二叉树
题目
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例2:
输入:root = [2,1,3]
输出:[2,3,1]
示例3:
输入:root = []
输出:[]
解题思路
//递归
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root)return nullptr;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
//广度优先 层序遍历
if(!root) return nullptr;
queue<TreeNode*> q;
TreeNode* tmp=new TreeNode(0);
q.push(root);
while(!q.empty()){
tmp=q.front();
q.pop();
swap(tmp->left,tmp->right);
if(tmp->left)q.push(tmp->left);
if(tmp->right)q.push(tmp->right);
}
return root;
}
};