本文最后更新于:2022年9月7日 晚上
翻转一棵二叉树。
示例:
输入:
输出:
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
Solution
参考 代码随想录
- 递归法
- 确定递归函数的参数和返回值
- 确定终止条件
- 确定单层递归的逻辑
这道题目使用前序遍历和后序遍历、层序遍历都可以,唯独中序遍历不行,因为中序遍历会把某些节点的左右孩子翻转了两次!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root==nullptr) return nullptr; invertTree(root->left); invertTree(root->right); swap(root->left, root->right); return root; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root==nullptr) return nullptr; stack<TreeNode *> stack; TreeNode *node = root; while (node != nullptr || !stack.empty()) { while (node) { stack.push(node); node = node->left; } node = stack.top(); stack.pop(); swap(node->left, node->right); node = node->left; } return root; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: TreeNode* invertTree(TreeNode* root) { queue<TreeNode*> que; if (root != NULL) que.push(root); while (!que.empty()) { int size = que.size(); for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); swap(node->left, node->right); if (node->left) que.push(node->left); if (node->right) que.push(node->right); } } return root; } };
|
java
| class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode tmp = root.left; root.left = root.right; root.right = tmp; invertTree(root.left); invertTree(root.right); return root; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode tmp = queue.poll(); TreeNode left = tmp.left; tmp.left = tmp.right; tmp.right = left; if (tmp.left != null) { queue.offer(tmp.left); } if (tmp.right != null) { queue.offer(tmp.right); } } return root; } }
|