本文介绍了镜像二进制搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是给出二进制搜索树根的代码,用于创建其镜像.
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).
更多推荐
镜像二进制搜索树
发布评论