繁体   English   中英

镜像二进制搜索树

[英]Mirror Binary Search Tree

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

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

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

是的,但不是非常Pythonic。

最好只是写

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

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

这是我的python代码以获取Binary搜索树的镜像。可能有一些不正确的缩进。

#Binary Tree Node

class Node:

    def __init__(self,item):
        self.data = item
        self.left = None
        self.right = None

#Binary search tree
class binarySearchTree:
    def __init__(self):
        self.root = Node(None)

    def mirror(self,node):

        if node is None:
            return False
        elif self.root.data == node:
            self.root.left,self.root.right = self.root.right,self.root.left
            if self.root.left != None:
                self._mirror(self.root.left)
                if self.root.right != None:
                    self._mirror(self.root.right)
            else:
                return self.root

    def _mirror(self,node):
        if node is None:
            return False
        else:
            node.left,node.right = node.right,node.left
            if node.left != None:
                self._mirror(node.left)
                if node.right != None:
                    self._mirror(node.right)

            else:
                return node
    def inorder_traverse(self):
        if self.root != None:
            self._inorder(self.root)

    def _inorder(self,cur):
        if cur != None:
            if cur.left is not None:
                self._inorder(cur.left)

            print(cur.data)

            if cur.right != None:
                self._inorder(cur.right)
def main():
    bst = binarySearchTree()
    bst.insert(7)
    bst.insert(1)
    bst.insert(0)
    bst.insert(3)
    bst.insert(2)
    bst.insert(5)
    bst.insert(4)
    bst.insert(6)
    bst.insert(9)
    bst.insert(8)
    bst.insert(10)
    bst.insert(11)
    bst.inorder_traverse()
    bst.mirror(7)
    bst.inorder_traverse()

输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM