剑指Offer-二叉树的镜像-python

题目描述:

操作给定的二叉树,将其变换为源二叉树的镜像。

思路:
递归或者非递归

递归:先前序遍历这棵树的每个节点,如果遍历到的节点有子节点,就交换它的两个字节点。
当交换完所有的非叶节点的左、右子节点之后,就得到了树的镜像。

非递归:

实现(递归):

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if root is None:
            return
        if root.left is None and root.right is None:
            return
        
        pTemp = root.left
        root.left = root.right
        root.right = pTemp
        
        if root.left:
            self.Mirror(root.left)
        if root.right:
            self.Mirror(root.right)

实现(非递归):

class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        if root == None:
            return
        stackNode = []
        stackNode.append(root)
        while len(stackNode) > 0:
            nodeNum = len(stackNode) - 1
            tree = stackNode[nodeNum]
            stackNode.pop()
            nodeNum -= 1
            if tree.left != None or tree.right != None:
                tree.left, tree.right = tree.right, tree.left
            if tree.left:
                stackNode.append(tree.left)
                nodeNum += 1
            if tree.right:
                stackNode.append(tree.right)
                nodeNum += 1

你可能感兴趣的:(编程,算法)