leetcode 112 路径总和

'''
leetcode 112 路径总和
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,
这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例: 
给定如下二叉树,以及目标和 sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

'''
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        # if root.left is None and root.right is None:
        #     if root.val==sum:
        #         return True
        #     else:
        #         return False
        if root is None:
            if sum==0:
                return True
            else:
                return False
        queue=[]
        # 队列,具有先进先出的性质,将链表的尾部作为队列尾部,将链表头部作为队列的头部
        # 仍然是沿着对于二叉树进行中序遍历的思路,对于二叉树中的每个节点都有唯一的父亲节点
        # 故而在每个节点处、以当前节点为路径起始点的局部路径总和的目标值是唯一的
        # 只需判断当前节点是否为叶子节点的特殊情况即可
        help_seq=[]
        queue.insert(0,root)
        help_seq.insert(0,sum)
        while(queue):
            temp=queue.pop(-1)
            temp_target=help_seq.pop(-1)

            # print(temp.val,temp_target)

            if temp.left is None and temp.right is None:
                if temp_target==temp.val:
                    return True
            else:
                if temp.left is not None:
                    queue.insert(0,temp.left)
                    help_seq.insert(0,temp_target-temp.val)
                if temp.right is not None:
                    queue.insert(0,temp.right)
                    help_seq.insert(0,temp_target-temp.val)
        return False

if __name__=="__main__":
    root=TreeNode(5)
    root.left=TreeNode(4)
    root.right=TreeNode(8)

    root.left.left=TreeNode(11)
    root.left.left.left = TreeNode(7)
    root.left.left.right = TreeNode(2)

    root.right.left=TreeNode(13)
    root.right.right = TreeNode(4)

    root.right.right.right = TreeNode(1)

    print(Solution().hasPathSum(root,22))

 

你可能感兴趣的:(python,leetcode)