Posts Path Sum - Binary Tree
Post
Cancel

Path Sum - Binary Tree

PROBLEM DESCRIPTION: Path Sum Binary Search Tree

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
class Solution {
  public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null)
      return false;

    sum = sum - root.val;
    if ((root.left == null) && (root.right == null))
      return (sum == 0);
    return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
  }
}
This post is licensed under CC BY 4.0 by the author.