题目描述
给你一棵二叉树的根节点 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 = []
输出:[]
思路
递归
- 交换左右子树
- 递归遍历根节点的左右子树进行交换
- 返回根节点
循环
- 初始化栈并将根节点压入栈中。
- 当栈不为空时:
- 弹出栈顶节点。
- 交换该节点的左右子节点。
- 将非空的左右子节点压入栈中。
- 返回根节点。
复杂度分析
递归方法
- 时间复杂度: O(n)
- 空间复杂度: O(h) (h 为二叉树的高度)
循环方法
- 时间复杂度: O(n)
- 空间复杂度: O(n)
code
递归
var invertTree = function (root) {
if (!root) return root
const temp = root.left
root.left = root.right
root.right = temp
invertTree(root.left)
invertTree(root.right)
return root
};
循环
var invertTree = function (root) {
const stack = [root]
while(stack.length > 0){
const node = stack.pop()
if(node){
// 交换左右子节点
const temp = node.left
node.left = node.right
node.right = temp
// 将子节点压入栈中
if(node.left) stack.push(node.left)
id(node.right) stack.push(node.right)
}
}
return root;
};