LeetCode-112:二叉树的路径和(Path Sum)

题目链接

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 = 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的非递归实现,用栈实现(使用python中列表模拟栈(先进后出FILO),即使用列表的append()pop()方法)

# 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方法,用队列实现(使用python中列表模拟队列(先进先出FIFO),即列表的insert()pop()方法)

# 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

猜你喜欢

转载自blog.csdn.net/qq_36653505/article/details/82227750