首页 > 其他 > 详细

树练习(3)

时间:2020-04-23 15:13:29      阅读:73      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

class Solution(object):
    def mirrorTree(self, root):
        if not root:
            return None;
        if not root.left and not root.right:
            return root;
        root.left,root.right=root.right,root.left;
        if root.left:
            self.mirrorTree(root.left);
        if root.right:
            self.mirrorTree(root.right);
        return root;

 

利用Python自带的交换值方式:

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        root.left,root.right = self.mirrorTree(root.right),self.mirrorTree(root.left)
        return root

使用非递归,栈的处理方式

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        stack=[root]
        while stack:
            node=stack.pop()
            if node.left:stack.append(node.left)
            if node.right:stack.append(node.right)
            node.left,node.right = node.right,node.left
        return root
            

 

树练习(3)

原文:https://www.cnblogs.com/topass123/p/12760624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!