问题
Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding (mirrored) right node. Each Binary Tree node has a value stored in a property called “value” and two children nodes stored in properties called “left” and “right,” respectively. Children nodes can either be Binary Tree nodes themselves or the None (null) value.
编写一个接受二叉树并将其反转的函数。换句话说**,该函数应该将树中的每个左节点交换为相应的(镜像的)右节点**。每个二叉树节点都有一个值存储在名为“value”的属性中,两个子节点分别存储在名为“left”和“right”的属性中。子节点可以是二叉树节点本身,也可以是None(null)值。

左边是原始的二叉树,右边是反转后的二叉树,可以看到左右节点进行了交换。
本文介绍如何反转一个二叉树,通过两种方法:循环处理和递归处理。循环处理利用队列,不断交换节点的左右子节点并入队。递归处理则直接交换节点的子节点并递归处理子节点。两种方法的时间复杂度均为O(N),但空间复杂度不同。
订阅专栏 解锁全文
714

被折叠的 条评论
为什么被折叠?



