数据结构:二叉树与二叉堆详解
1. 二叉树的中序遍历与反转
中序遍历与前序、后序遍历类似,但它是在两次递归调用之间打印节点的值(或执行其他操作)。使用中序遍历时,遍历顺序是从左子树到根节点再到右子树。
反转二叉树
知名包管理器 Homebrew 的创造者 Max Howell 在谷歌面试软件工程师职位时,因无法在白板上反转二叉树而被拒。反转二叉树意味着交换树中所有节点的左右子节点。
可以使用广度优先搜索(BFS)来反转二叉树,以下是实现代码:
class BinaryTree:
def __init__(self, value):
self.key = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = BinaryTree(value)
else:
bin_tree = BinaryTree(value)
bin_tree.left_child = self.left_child
self.left_child = bin_tree
def insert_right(self, value):
if self.right_child == None:
超级会员免费看
订阅专栏 解锁全文
1950

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



