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 s;
s.push(root);
while(s.size())
{
TreeNode* cur = s.top();
//swap(cur->left, cur->right);
//等价于下面三行
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 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;
}
};
推荐阅读
- leetcode刷题实录|leetcode226 翻转二叉树
- 刷题|leetcode226翻转二叉树(JAVA版)
- leetcode|LeetCode226翻转二叉树(递归)
- 二叉树|leetcode 226 翻转二叉树
- 春招|【Android春招每日一练】(三十二) LeetCode Hot 10题
- 春招|【Android春招每日一练】(三十四) LeetCode Hot 5题+总结(完)
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解