镜像二进制搜索树

编程入门 行业动态 更新时间:2024-10-24 08:23:02
本文介绍了镜像二进制搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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).

更多推荐

镜像二进制搜索树

本文发布于:2023-11-29 08:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:镜像

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!