翻转二叉树
🟢 简单题目描述
给你一棵二叉树的根节点 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]提示
- 树中节点数目范围在
[0, 100]内 -100 <= Node.val <= 100
解法一
参考答案 (2 个标签)
递归 O(n)
思路
交换左右子节点,然后递归处理左右子树。
代码实现
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
function invertTree(root) {
if (root === null) return null;
const temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(h)
解法二
参考答案 (3 个标签)
BFS 迭代 O(n)
思路
使用队列遍历每个节点,交换其左右子节点。
代码实现
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
function invertTree(root) {
if (root === null) return null;
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
const temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return root;
}复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(w)
