Python实现"相同的树"的三种方法

给定两颗二叉树,判断它们是否相同

如果两棵树的结构和对应结点的值均相等,就认为它们是相同的树

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

1:两颗树分别递归转列表,判断列表是否相同

def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        p_list = self.tree_to_list(p)
        q_list = self.tree_to_list(q)
        if p_list == q_list:
            return True
        else:
            return False

    def tree_to_list(self, tree):      #递归
        if not tree:
            return None
        if not tree.left and tree.right:    #判断树的结构,如果树存在右节点却不存在左结点,将左节点添加为[None],用来区分树的结构
            new_list = [tree.val]+[None]
            right = self.tree_to_list(tree.right)       #只递归树的右节点
            if not right:    
                return new_list
            else:
                return new_list + right
        left = self.tree_to_list(tree.left)       #递归左节点
        if not left:
            new_list = [tree.val]
        else:
            new_list = [tree.val]+left
        right = self.tree_to_list(tree.right)    #递归右结点
        if not right:
            return new_list
        else:
            return new_list+right

2:两棵树自身同步递归,判断是否相同

def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p==None and q==None:
            return True
        if p!=None and q==None:
            return False
        if p==None and q!=None:
            return False
        if p.val!=q.val:
            return False
        left = self.isSameTree(p.left, q.left)
        right = self.isSameTree(p.right, q.right)
        return left and right

3:迭代

def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        nodeList = [p,q]
        while nodeList:
            symmetricLeft = nodeList.pop(0)
            symmetricRight = nodeList.pop(0)
            if not symmetricLeft and not symmetricRight:
                continue
            if not symmetricLeft or not symmetricRight:
                return False
            if symmetricLeft.val != symmetricRight.val:
                return False
            nodeList.append(symmetricLeft.left)
            nodeList.append(symmetricRight.left)
            nodeList.append(symmetricLeft.right)
            nodeList.append(symmetricRight.right)
        return True

算法题来自:https://leetcode-cn.com/problems/same-tree/description/

你可能感兴趣的:(Algorithms)