之前写的时候感觉有点问题,又试了一下。

大概就是这样, 交换左右子树,再对子树递归,之前写的时候好像判断了一下左右是否存在,其实不必要。

class Node(object):
    def __init__(self, val, l_node, r_node):
        self.l_node = l_node
        self.r_node = r_node
        self.val = val


def binary_tree_reverse(node):
    if node:
        node.l_node, node.r_node = node.r_node, node.l_node
        binary_tree_reverse(node.l_node)
        binary_tree_reverse(node.r_node)


if __name__ == '__main__':
    n7 = Node(7, None, None)
    n6 = Node(6, None, None)
    n5 = Node(5, None, None)
    n4 = Node(4, None, None)
    n3 = Node(3, n6, n7)
    n2 = Node(2, n4, n5)
    n1 = Node(1, n2, n3)

    binary_tree_reverse(n1)