一、题目内容 简单
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
示例 2:
输入:root = [2,1,3] 输出:[2,3,1]
示例 3:
输入:root = [] 输出:[]
提示:
三、具体代码
/*** @param {TreeNode} root* @return {TreeNode}*/var invertTree = function (root) {if (!root) return null;return new TreeNode(root.val, invertTree(root.right), invertTree(root.left));};/*** 时间复杂度:O(n)* 空间复杂度:O(n)*/
四、其他解法
迭代法
深度优先遍历1
如果我们这样翻转应该还可以这样实现。从根节点开始,翻转其左右的子树。接着进入左右子树 A 和 B。
以 A 为根节点,翻转 A 的子树,同理翻转 B 的子树。然后一层层得翻转。
按照这个思路,我们应该声明一个栈,把 A 节点 的左右子节点,压入栈,目的是等待下一次拿出这两个节点,翻转他们各自的左右子树。
我们把 A 节点的左右子树翻转,然后继续循环,直到栈为空,说明翻转完成。
/*** @param {TreeNode} root* @return {TreeNode}*/var invertTree = function (root) {if (!root) return null;const stack = [root];const invertNode = (root, left, right) => {root.left = right;root.right = left;}while (stack.length) {const node = stack.pop();node.right && stack.push(node.right);node.left && stack.push(node.left);invertNode(node, node.left, node.right);}return root;};/*** 时间复杂度:O(n)* 空间复杂度:O(n)*/
深度优先遍历2
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*//*** @param {TreeNode} root* @return {TreeNode}*/var invertTree = function (root) {if (!root) return nullconst queue = [root]while (queue.length) {const node = queue.shift()if (node.left) queue.push(node.left)if (node.right) queue.push(node.right)const tmp = node.leftnode.left = node.rightnode.right = tmp}return root};
输入:root = [4,2,7,1,3,6,9] 
输出:[4,7,2,9,6,3,1]
输入:root = [2,1,3]
输出:[2,3,1]