跳至主要內容

226. Invert Binary Tree


226. Invert Binary Treeopen in new window

🟢   🔖  深度优先搜索 广度优先搜索 二叉树  🔗 LeetCodeopen in new window

题目

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

Input: root = [4,2,7,1,3,6,9]

Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]

Output: [2,3,1]

Example 3:

Input: root = []

Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

题目大意

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

解题思路

可以递归遍历(dfs)二叉树,交换每个节点的左右子节点,即可生成二叉树的镜像。

  • 终止条件: 当节点 root 为空时(即越过叶节点),则返回 null
  • 初始化节点 temp ,用于暂存 root 的左子节点;
  • 递归右子节点 mirrorTree(root.right) ,并将返回值作为 root 的左子节点 。
  • 递归左子节点 mirrorTree(temp) ,并将返回值作为 root 的右子节点 。
  • 返回当前节点 root

代码

/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function (root) {
	if (root == null) return null;
	let temp = root.left;
	root.left = mirrorTree(root.right);
	root.right = mirrorTree(temp);
	return root;
};

相关题目

相关题目
- [2415. 反转二叉树的奇数层](https://leetcode.com/problems/reverse-odd-levels-of-binary-tree)