首页 > 解决方案 > Python 3 出现此代码错误(另一棵树的子树)

问题描述

当我运行此代码时,它应该给我 false,但它只返回 true 特别针对此 inputL [3,4,5,1,2,null,null,0] [4,1,2]

概念是:给定两个非空二叉树 s 和 t,检查树 t 是否与 s 的子树具有完全相同的结构和节点值。s 的子树是由 s 中的一个节点和该节点的所有后代组成的树。树 s 也可以被认为是它自己的子树。

      class Solution:
        src = []
        def traverseToVal(self, s, v):
            if not s:
                return
            if s.val == v:
                self.src.append(s)
                return
            self.traverseToVal(s.left, v)
            self.traverseToVal(s.right, v)
            
        def isSame(self, s, t):
            if not s and not t:
                return True
            
            if s and not t:
                return False
            
            if t and not s:
                return False
            
            return s.val == t.val and self.isSame(s.left, t.left) and self.isSame(s.right, t.right)
        
        def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
            if not s and not t:
                return True
            
            if s and not t:
                return False
            
            if t and not s:
                return False
            
            # stands for "subtree root candidate"
            self.traverseToVal(s, t.val)
            if not self.src:
                return False
            # print(self.src)
            
            out = []
            for src in self.src:
                out.append(self.isSame(src, t))
            return any(out)

标签: pythontree

解决方案


推荐阅读