题解 | #二叉树的镜像#

二叉树的镜像

https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7

#coding:utf-8
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pRoot TreeNode类 
# @return TreeNode类
#

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

class Solution:
    def Mirror(self , pRoot ):
        # write code here
        pRoot2 = pRoot
        path1 = []
        path2 = []
        #self.dfs(pRoot)
        self.bfs(pRoot)
        return pRoot
    
    def dfs(self, node):
        if node == None:
            return node
        left = self.dfs(node.left)
        right = self.dfs(node.right)
        node.left = right
        node.right = left
        return node

    def bfs(self, node):
        if node == None:
            return node
        stack = []
        stack.append(node)
        while len(stack) > 0:
            cur_node = stack.pop()
            if cur_node.left != None:
                stack.append(cur_node.left)
            if cur_node.right != None:
                stack.append(cur_node.right)
			//交换左右
            tmp = cur_node.left 
            cur_node.left = cur_node.right 
            cur_node.right = tmp
        
        return node





全部评论

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 11:31
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务