二叉树节点左右孩子交换算法:递归实现与优化
这道题可以使用递归的方式实现。对于每个节点,交换其左右子树,然后递归交换其左右子树。
具体实现如下:
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
# 交换左右子树
root.left, root.right = root.right, root.left
# 递归交换左右子树
self.invertTree(root.left)
self.invertTree(root.right)
return root
时间复杂度为 $O(n)$,其中 $n$ 是二叉树的节点数。因为我们需要遍历每个节点一次。空间复杂度为 $O(h)$,其中 $h$ 是二叉树的高度。在最坏情况下,二叉树退化为链表,高度为 $n$,空间复杂度为 $O(n)$。在最好情况下,二叉树为完全二叉树,高度为 $\log n$,空间复杂度为 $O(\log n)$。
原文地址: https://www.cveoy.top/t/topic/nF9t 著作权归作者所有。请勿转载和采集!