112. 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.

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.

使用递归进行计算,遍历所有的叶结点

Runtime: 96 ms, faster than 100.00% of C# online submissions for Path Sum.
Memory Usage: 24 MB, less than 68.75% of C# online submissions for Path Sum.
public bool HasPathSum(TreeNode root, int sum)
        {
            if (root == null)
            {
                return false;
            }
            return Sum(root, sum, 0);
        }

        public bool Sum(TreeNode node, int target, int tempSum)
        {
            tempSum = tempSum + node.val;
            var left = node.left;
            var right = node.right;
            if (left == null && right == null)
            {
                return tempSum == target;
            }
            else if (left != null && right == null)
            {
                return Sum(left, target, tempSum);
            }
            else if (left == null && right != null)
            {
                return Sum(right, target, tempSum);
            }
            else if (left != null && right != null)
            {
                bool flag1 = Sum(left, target, tempSum);
                if (flag1)
                {
                    return true;
                }
                bool flag2 = Sum(right, target, tempSum);
                if (!flag2)
                {
                    return false;
                }
            }

            return true;
        }
原文地址:https://www.cnblogs.com/chucklu/p/10695382.html