Same Tree

题目

给予两棵二叉树,判断这两棵树是否相等(即各节点的值都一样)

解题思路

分别遍历两棵二叉树,并用列表分别存储这两棵树的节点的值,比较这两个列表就可以了

class Solution:
    # @param {TreeNode} p
    # @param {TreeNode} q
    # @return {boolean}
    def isSameTree(self, p, q):
        if (not p) and (not q):
            return True
        if (not p) and q:
            return False
        if (not q) and p:
            return False
        plist = self.pTree(p)
        qlist = self.qTree(q)
        if plist != qlist:
            return False
        return True
    
    def pTree(self, root):
        queue = []
        plist = []
        plist.append(root.val)
        queue.append(root)
        
        while queue:
            root = queue.pop(0)

            if root.left:
                queue.append(root.left)
                plist.append(root.left.val)
            if not root.left:
                plist.append('null')
            if root.right:
                queue.append(root.right)
                plist.append(root.right.val)
            
            if not root.right:
                plist.append('null')

        return plist
        
    def qTree(self, root):
        queue = []
        qlist = []
        qlist.append(root.val)
        queue.append(root)
        
        while queue:
            root = queue.pop(0)

            if root.left:
                queue.append(root.left)
                qlist.append(root.left.val)
            if not root.left:
                qlist.append('null')
            if root.right:
                queue.append(root.right)
                qlist.append(root.right.val)
            if not root.right:
                qlist.append('null')

        return qlist

相关文章:

  • 2022-03-09
  • 2021-09-04
  • 2021-09-02
  • 2021-05-20
  • 2021-07-30
  • 2022-12-23
猜你喜欢
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-01-05
  • 2021-09-10
  • 2021-08-18
相关资源
相似解决方案