给你一棵二叉树的根节点
root,翻转这棵二叉树,并返回其根节点。
解法1 递归
思路
翻转这棵树其实本质上就是左右子树的交换。递归的时候拿到左右子树的节点,然后交换节点,最后返回根节点即可。
终止条件是当前节点为空时返回 null。
代码
function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) {
return null;
}
const left = invertTree(root.right);
const right = invertTree(root.left);
root.left = left;
root.right = right;
return root;
};
时空复杂度
时间复杂度:O(n)
空间复杂度:O(h)
解法2 队列遍历
代码
function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) {
return null;
}
const queue = [root];
while (queue.length) {
const node = queue.shift();
[node.left, node.right] = [node.right, node.left];
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return root;
};
时空复杂度
时间复杂度:O(n)
空间复杂度:O(n),没有stackoverflow的风险