검지 offerpython 버전 27.두 갈래 나무의 거울

8301 단어
"""
 , 。
"""
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    #  
    def MirrorRecursively(self, pNode):
        if pNode == None:
            return
        if pNode.left == None and pNode.right == None:
            return

        pNode.left, pNode.right = pNode.right, pNode.left

        if pNode.left:
            self.MirrorRecursively(pNode.left)
        if pNode.right:
            self.MirrorRecursively(pNode.right)

    #  
    def MirrorNoRecursion(self, pNode):
        if pNode == None:
            return
        nodeQue = [pNode]
        while len(nodeQue) > 0:
            curLevel, count = len(nodeQue), 0
            while count < curLevel:
                count += 1
                pRoot = nodeQue.pop(0)
                pRoot.left, pRoot.right = pRoot.right, pRoot.left
                if pRoot.left:
                    nodeQue.append(pRoot.left)
                if pRoot.right:
                    nodeQue.append(pRoot.right)

if __name__ == "__main__":
    pNode1 = TreeNode(8)
    pNode2 = TreeNode(6)
    pNode3 = TreeNode(10)
    pNode4 = TreeNode(5)
    pNode5 = TreeNode(7)
    pNode6 = TreeNode(9)
    pNode7 = TreeNode(11)

    pNode1.left = pNode2
    pNode1.right = pNode3
    pNode2.left = pNode4
    pNode2.right = pNode5
    pNode3.left = pNode6
    pNode3.right = pNode7

    S = Solution()
    S.MirrorRecursively(pNode1)
    print(pNode1.right.left.val)

좋은 웹페이지 즐겨찾기