112. 路径总和
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
思路:利用递归思想,sum - root.val的值是否为零,不为零就进行递归运算,为零判断是否为独立的根节点。
代码:
# 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 root is None:
return False
sum = sum - root.val
if sum == 0:
if root.left is None and root.right is None:
return True
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
二叉树的三种(递归)遍历方式
二叉树先序遍历
代码如下:
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
path = []
def order(root):
path.append(root.val)
if root.left is not None:
order(root.left)
if root.right is not None:
order(root.right)
order(root)
return path
二叉树中序遍历
代码如下:
# 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
path = []
def order(root):
if root.left is not None:
order(root.left)
path.append(root.val)
if root.right is not None:
order(root.right)
order(root)
return path
二叉树的后序遍历
代码如下:
# 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 postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
path = []
def order(root):
if root.left is not None:
order(root.left)
if root.right is not None:
order(root.right)
path.append(root.val)
order(root)
return path
5663



被折叠的 条评论
为什么被折叠?



