面试思路

二叉树的镜像

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

Python测试:

// An highlighted block
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
            return root
        if not root.right and not root.left:
            return root
        if root.right or root.left:
            t=root.right
            root.right=root.left
            root.left=t
        self.Mirror(root.right)
        self.Mirror(root.left)
        return root

    def getBSTwithPreTin(self, pre, tin):
        if len(pre) == 0 | len(tin) == 0:
            return None

        root = treeNode(pre[0])
        for order, item in enumerate(tin):
            if root.val == item:
                root.left = self.getBSTwithPreTin(pre[1:order + 1], tin[:order])
                root.right = self.getBSTwithPreTin(pre[order + 1:], tin[order + 1:])
                return root

class treeNode:
    def __init__(self, x):
        self.left = None
        self.right = None
        self.val = x

def pre_order(root):
    if root is None:
        return
    else:
        print(root.val)
        pre_order(root.left)
        pre_order(root.right)

   #中序遍历
def mid_order(root):
        if root is None:
            return
        else:
            mid_order(root.left)
            print(root.val)
            mid_order(root.right)


if __name__ == '__main__':
    solution = Solution()
    preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8]
    middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6]
    treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)

    root = solution.Mirror(treeRoot1)
    print(pre_order(root))
    
    print(mid_order(root))

前序镜像结果:
在这里插入图片描述
中序:在这里插入图片描述
https://blog.csdn.net/qq_34364995/article/details/80787116

总结

二叉树的镜像:https://blog.csdn.net/qq_38441207/article/details/88687321

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值