/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root ==nullptr ) return root;
queue<TreeNode*>qu; //这里是用到了层序遍历 所以需要一个队列
qu.push(root);
while(!qu.empty())
{
TreeNode * node = qu.front();
qu.pop();
if(node->left!=nullptr) qu.push(node->left);//把左子节点放入队列
if(node->right!=nullptr) qu.push(node->right);//把右子节点放入队列
//交换已经不再队列的node的左右指针
TreeNode* temp = node->left;
node->left = node -> right;
node -> right = temp;
}
return root;
}
};
网友评论