Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 경로 합


트리 하나와 합이 있다고 가정합니다. 우리는 그 경로를 따를 경우 주어진 합과 일치하는 합을 얻을 수 있는 하나의 경로를 찾아야 합니다. 트리가 [0,-3,9,-10, null,5]이고 합이 14라고 가정하면 경로는 0 → 9 → 5

입니다.

Python의 경로 합

이 문제를 해결하기 위해 다음 단계를 따릅니다.

  • 루트가 null이면 False를 반환합니다.

  • 왼쪽 및 오른쪽 하위 트리가 비어 있으면 sum – root.val =0일 때 true를 반환하고, 그렇지 않으면 false

  • return solve(root.left, sum – root.val) 또는 solve(root.right, sum – root.val)

더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −

예시

# Definition for a binary tree node.
class TreeNode(object):
   def __init__(self, x):
      self.data = x
      self.left = None
      self.right = None
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         if data is not None:
            temp.right = TreeNode(data)
         else:
            temp.right = TreeNode(0)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def hasPathSum(self, root, sum):
      """
      :type root: TreeNode
      :type sum: int
      :rtype: bool
      """
      if not root :
         return False
      if not root.left and not root.right and root.data is not None:
         return sum - root.data == 0
      if root.data is not None:
         return self.hasPathSum(root.left, sum-root.data) or self.hasPathSum(root.right, sum-root.data)
tree1 = make_tree([0,-3,9,-10,None,5])
ob1 = Solution()
print(ob1.hasPathSum(tree1, 14))

입력

tree1 = make_tree([0,-3,9,-10,None,5])

출력

True