树的遍历 | 路径总和

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.
Note: A leaf is a node with no children.

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.

思路1: 遍历

在遍历的过程中,保留从根节点到当前节点的值,在访问到某个节点时,如果该节点为叶子节点,且sum = 0,则返回True

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        dfs
        """
        if root is None:
            return False
        root.sum = sum - root.val
        stack = [root]
        while len(stack):
            while root:
                left = root.left
                if left:
                    left.sum = root.sum - left.val
                    stack.append(left)
                root = left
                
            root = stack.pop()
            if root:
                if root.sum == 0 and root.left is None and root.right is None:
                    return True
                if root.right:
                    right = root.right
                    right.sum = root.sum - right.val
                    stack.append(right)
                    root = right
        return False

思路2: 递归,

递归判断左子树或右子树是否存在 sum - root.val 的路径。

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        dfs
        """
        if root is None:
            return False
        sum = sum  - root.val
        if sum == 0 and root.left == None and root.right == None:
            return True
        else:
            return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
原文地址:https://www.cnblogs.com/xmxj0707/p/10381227.html