美文网首页算法,写代码
[easy+][Tree] 101.Symmetric Tree

[easy+][Tree] 101.Symmetric Tree

作者: 小双2510 | 来源:发表于2017-11-08 02:57 被阅读0次

原题是:

Screen Shot 2017-11-07 at 1.54.16 PM.png

思路是:

将给定的整颗树,进行复制。对复制的树,进行左右翻转操作,再对比翻转好的树,和原先的树是否是一样的树。
这里要注意的是,我犯过一个错误,将原先的树翻转之后,丢失原先的树了。所以增加了一个迭代函数对原先的树进行拷贝。

代码是:

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

class Solution(object):
    # deep copy tree root
   
        
    def reverse(self,root):
        if root == None:
            return root
        else:
            tmp = root.left
            root.left = root.right
            root.right = tmp
            root.left = self.reverse(root.left)
            root.right = self.reverse(root.right)
            return root
    
    def isSame(self,root1,root2):
        
        if root1 == None and root2 == None:
            return True
        elif not (root1 and root2):
            return False
        #elif not (root1.left or root1.right or root2.left or root2.right) and root1.val == root2.val:
        #    return True
        elif root1.val != root2.val:
            return False
        
        return self.isSame(root1.left,root2.left) and self.isSame(root1.right,root2.right)        
    

    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        root = copy.deepcopy(root)
        root_reverse = self.reverse(root_reverse)
        
        return self.isSame(root,root_reverse)

相关文章

  • [easy+][Tree] 101.Symmetric Tree

    原题是: 思路是: 将给定的整颗树,进行复制。对复制的树,进行左右翻转操作,再对比翻转好的树,和原先的树是否是一样...

  • DFS-special

    Validate Binary Search Tree Same Tree (基础) 101.symmetric ...

  • 101.Symmetric Tree

    判断树是否对称,每次将比对的两个节点的左右节点与右左节点对比: l->left==r->right && l->r...

  • 二叉树的相似、镜像问题

    二叉树的镜像: 100.Same Tree(二叉树是否相同) 101.Symmetric Tree(二叉树是否对称)

  • [easy+][Tree] 563.Binary Tree Ti

    原题是: 思路是: 我一开始的思路是:第一步,写两个函数,第一个函数对一个给定的root,求以它为root的这棵树...

  • [easy+][Tree]543.

    原题是: Given a binary tree, you need to compute the length ...

  • [easy+][Tree]572.Subtree of Anot

    原题是: Given two non-empty binary trees s and t, check whet...

  • [easy+][Tree]110.Balanced Binary

    原题是: 思路是: 这个题与前面所刷的树的递归问题的一点区别在于:当前节点要判断是否平衡,除了需要知道它的左右子节...

  • [easy+][Tree][review]257.Binary

    原题是: 思路是: 这个题前面所有题的不同之处在于,从上到下的过程中,需要上一层的值,所以把上一层的值作为参数传入...

  • [easy+][Tree]112. Path Sum

    path sum 有好几题,是一个系列。 原题是: Given a binary tree and a sum, ...

网友评论

    本文标题:[easy+][Tree] 101.Symmetric Tree

    本文链接:https://www.haomeiwen.com/subject/rbasmxtx.html