112. Path Sum [easy] (Python)

来源:互联网 发布:广告平面设计的软件 编辑:程序博客网 时间:2024/05/17 04:18

题目链接

https://leetcode.com/problems/path-sum/

题目原文

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

题目翻译

给定一个二叉树及一个和数sum,判断这个树是否有一条从根到叶的路径,这条路径上所有数之和为sum。比如,给定sum=22,二叉树为:

              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

那么应该返回true,因为存在路径 5->4->11->2 ,其和为22。

思路方法

思路一

用深度优先搜索(DFS)遍历所有可能的从根到叶的路径,要注意每深一层要从和中减去相应节点的数值。下面是递归实现的代码。

代码

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass 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:            return True if sum == root.val else False        else:            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)

思路二

DFS的非递归实现,用栈实现。

代码

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def hasPathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: bool        """        stack = [(root, sum)]        while len(stack) > 0:            node, tmp_sum = stack.pop()            if node:                if not node.left and not node.right and node.val == tmp_sum:                    return True                stack.append((node.right, tmp_sum-node.val))                stack.append((node.left, tmp_sum-node.val))        return False

思路三

BFS方法,用队列实现。

代码

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def hasPathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: bool        """        queue = [(root, sum)]        while len(queue) > 0:            node, tmp_sum = queue.pop()            if node:                if not node.left and not node.right and node.val == tmp_sum:                    return True                queue.insert(0, (node.right, tmp_sum-node.val))                queue.insert(0, (node.left, tmp_sum-node.val))        return False

思路四

如果说上面都是比较常规的方法,那么后序遍历算是比较新奇的解法了。虽然也用的栈,但后序遍历的一大好处是它直接将路径保存在栈中,每次进入不同的层不需要记录当前的和。算是与DFS各有所长吧。

代码

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def hasPathSum(self, root, sum):        """        :type root: TreeNode        :type sum: int        :rtype: bool        """        pre, cur = None, root        tmp_sum = 0        stack = []        while cur or len(stack) > 0:            while cur:                stack.append(cur)                tmp_sum += cur.val                cur = cur.left            cur = stack[-1]            if not cur.left and not cur.right and tmp_sum == sum:                return True            if cur.right and pre != cur.right:                cur = cur.right            else:                pre = cur                stack.pop()                tmp_sum -= cur.val                cur = None        return False

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51595815

0 0
原创粉丝点击