leetcode-92 翻转二叉树
2019-03-02 本文已影响0人
橘子煲汤
/**
* 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;
}
};