镜像二进制搜索树 [英] Mirror Binary Search Tree

查看:65
本文介绍了镜像二进制搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是给出二进制搜索树根的代码,用于创建其镜像.

This is a code that given a root of the binary search tree, is to create its mirror.

def mirror(root):
    if root is None:
        pass
    else:
        mirror(root.left)
        mirror(root.right)
        temp = root.left
        root.left = root.right
        root.right = temp

首先,这段代码正确吗?这里的递归是否应该首先到达树的叶子,然后在展开时切换引用?

Firstly, is this code right and also is the recursion here supposed to first get to the leaves of the tree first and then switch the references when unwinding?

推荐答案

是正确的,但不是Pythonic.

It's right, but not very Pythonic.

更好地写作

def mirror(root):
    if root is None:
        return
    mirror(root.left)
    mirror(root.right)
    root.left, root.right = root.right, root.left

对于此问题,您可以按任何顺序进行递归(在父级之前或之后将叶子反向).

For this problem, you could recurse in either order (either reversing the leaves before the parents or after).

这篇关于镜像二进制搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆