LeetCode 226翻转二叉树
- 题目简述:翻转一棵二叉树。
- 输入:[4, 2, 7, 1, 3, 6, 9] 输出:[4, 7, 2, 9, 6, 3, 1]
- 思路:递归遍历整棵二叉树,遍历到每个节点时交换左右儿子。时间复杂度
O(n)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return 0;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return 0;
stack<TreeNode*> s;
s.push(root);
while(s.size())
{
TreeNode* cur = s.top();
TreeNode* tmp = cur->right;
cur->right = cur->left;
cur->left = tmp;
s.pop();
if(cur->left) s.push(cur->left);
if(cur->right) s.push(cur->right);
}
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
while(q.size())
{
TreeNode* cur = q.front();
swap(cur->left, cur->right);
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
return root;
}
};