112. Path Sum [easy] (Python)
2016-06-06 15:28
585 查看
题目链接
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->2which 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 = None 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: 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 = None class 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 = None class 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 = None class 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,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857856.html
相关文章推荐
- 误删python setuptools的解决方案
- Python正则匹配 -> 模块和基本函数
- python生成器(转)
- Python实现MySQL DBA小工具一例 推荐
- 浅析AST抽象语法树及Python代码实现
- python set
- python logging使用
- Python学习笔记 —— 数字类型【Numbers】及常用方法
- Python装饰器与面向切面编程
- Python字符编码
- 第二节Python特征
- 第一节 Python 简历 (蟒蛇)
- selenium + python 添加等待时间
- Python爬虫实战(1):爬取Drupal论坛帖子列表
- 我的python之路【第二篇】数据类型与方法
- Python爬虫实战(1):爬取Drupal论坛帖子列表
- python07-生成器与迭代器
- 边做边学Python Flask Web开发(3)-- Flask Hello World!
- Python学习1
- 增强你的python见识