二叉树的镜像树

思路:交换左右子树,时间复杂度O(n),先序遍历

class TreeNode(object):

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

        self.data = data

        self.left = left

        self.right = right

A = TreeNode("A")

B = TreeNode("B")

C = TreeNode("C")

D = TreeNode("D")

E = TreeNode("E")

F = TreeNode("F")

G = TreeNode("G")

A.left = B

A.right = C

A.data = 8

B.left = D

B.right = E

B.data = 6

C.left = F

C.right = G

C.data = 10

D.left = None

D.right = None

D.data = 5

E.left = None

E.right = None

E.data = 7

F.left = None

F.right = None

F.data = 9

G.left = None

G.right = None

G.data = 11

 

def TreeMirro(tree_node,l):

    if tree_node is None or (tree_node.left isNone and tree_node.right is None):

        l.append(tree_node.data)

        return tree_node

    tree_node.left,tree_node.right =tree_node.right,tree_node.left

    l.append(tree_node.data)

    print "---"

    if tree_node.left:

        TreeMirro(tree_node.left,l)

    if tree_node.right:

        TreeMirro(tree_node.right,l)

    return l

l = []

print TreeMirro(A,l)

#first [8, 6, 5, 7, 10, 9,11]

#chang [8, 10, 11, 9, 6, 7,5]


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页