Mirror Binary Search Tree

拜拜、爱过 提交于 2019-12-25 04:59:15

问题


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?


回答1:


It's right, but not very Pythonic.

Better to just write

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




回答2:


Here is my python code to get mirror image of Binary search tree.There might be some incorrect indentations.

#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()

output:

enter image description here



来源:https://stackoverflow.com/questions/15325281/mirror-binary-search-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!