【Leetcode】226. 翻转二叉树
2019-03-30 19:53
337 查看
QUESTION
easy
题目描述
翻转一棵二叉树。
示例:
输入: 4 / \ 2 7 / \ / \ 1 3 6 9 输出: 4 / \ 7 2 / \ / \ 9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的:
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
说明
无
SOLUTION
看到备注,相信这个老哥崩溃了
方法一(递归)
这道题其实很好写,我被谷歌吓到了。
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return NULL; TreeNode *tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; } };
方法二(非递归)
class Solution { public: TreeNode* invertTree(TreeNode* root) { queue<TreeNode*> q; if(root) q.push(root); while(!q.empty()){ TreeNode *curr = q.front(); if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); TreeNode *tmp = curr->left; curr->left = curr->right; curr->right = tmp; q.pop(); } return root; } };
相关文章推荐
- 翻转二叉树(leetcode-226)
- [数据结构][Leetcode]翻转二叉树
- LeetCode226--翻转二叉树
- LeetCode Invert Binary Tree 翻转二叉树
- 【LeetCode】226. Invert Binary Tree 二叉树翻转
- leetcode - 226 - 翻转二叉树
- [LeetCode] 226 翻转二叉树
- 【LeetCode】Invert Binary Tree 翻转二叉树 - Easy++
- leetcode 951. 翻转等价二叉树
- Leetcode 951:翻转等价二叉树
- LeetCode 226 Invert Binary Tree(翻转二叉树)
- leetCode之翻转二叉树
- leetcode 226 Invert Binary Tree 翻转二叉树
- leetcode 226 Invert Binary Tree 翻转二叉树
- leetcode 226 Invert Binary Tree 翻转二叉树
- [LeetCode] Invert Binary Tree - 二叉树翻转系列问题
- [LeetCode] Invert Binary Tree 翻转二叉树
- Leetcode 226.翻转二叉树
- 将一个二叉树左右翻转(Java 版)
- [2016/11/17]翻转二叉树