python 刷leetcode时如何传进去二叉树而非数组

python 刷leetcode时如何传进去二叉树而非数组,第1张

python 刷leetcode时如何传进去二叉树而非数组
# 定义树
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# 将数组转为二叉树
class Tree(object):
    def __init__(self):
        self.root = None
    def construct_tree(self, values=None):
        if not values:
            return None
        self.root = TreeNode(values[0])
        queue = deque([self.root])
        leng = len(values)
        nums = 1
        while nums < leng:
            node = queue.popleft()
            if node:
                node.left = TreeNode(values[nums]) if values[nums] else None
                queue.append(node.left)
                if nums + 1 < leng:
                    node.right = TreeNode(values[nums+1]) if values[nums+1] else None
                    queue.append(node.right)
                    nums += 1
                nums += 1
        return self.root


# leetcode实现

class Solution:
    def haspathsum(self, root: TreeNode, targetsum: int) -> bool:
        def isornot(root, targetsum) -> bool:
            if (not root.left) and (not root.right) and targetsum == 0:
                return True  # 遇到叶子节点,并且计数为0
            if (not root.left) and (not root.right):
                return False  # 遇到叶子节点,计数不为0
            if root.left:
                targetsum -= root.left.val  # 左节点
                if isornot(root.left, targetsum): return True  # 递归,处理左节点
                targetsum += root.left.val  # 回溯
            if root.right:
                targetsum -= root.right.val  # 右节点
                if isornot(root.right, targetsum): return True  # 递归,处理右节点
                targetsum += root.right.val  # 回溯
            return False
        if root == None:
            return False  # 别忘记处理空treenode
        else:
            print(root.val)
            return isornot(root, targetsum - root.val)

# main
a = Solution()
num = [5,4,8,11,None,13,4,7,2,None,None,None,1]
# 先实现二叉树
t = Tree()
root = t.construct_tree(num)
targetSum = 22
# 传进来的是二叉树
print(a.haspathsum(root, targetSum))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5701191.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存