LeetCode-226. 翻转二叉树
难度:简单
翻转一棵二叉树。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
/*
1.递归方法
if(!root)return NULL;
TreeNode *left = root->left;
TreeNode *right = root->right;
root->left = right;
root->right = left;
invertTree(left);
invertTree(right);
return root;
*/
/*
2.前序遍历方法
*/
if( !root )return nullptr;
queue<TreeNode*> q;
q.push(root);
int size;
TreeNode* cur;
TreeNode* left;
TreeNode* right;
while( !q.empty() ){
size = q.size();
while(size--){
cur = q.front();
q.pop();
left = cur->left;
right = cur->right;
cur->left = right;
cur->right = left;
if(left)q.push(left);
if(right)q.push(right);
}
}
return root;
}
};
执行结果:
通过
执行用时:
0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:
9.5 MB, 在所有 C++ 提交中击败了39.72%的用户
通过测试用例:
77 / 77