Given a binary tree and a target sum, determine if there is a root-to-leaf path in this tree where the sum of all the node values along the path equals the target sum.
Note: A leaf is a node with no children.
Given the following binary tree and the target sum sum = 22
, return true
, because there exists a root-to-leaf path with a sum of 22
: 5->4->11->2
.
Simply use depth-first search. First, handle the boundary conditions. If the node is null
, return false
directly. Then add the tmp
value to the node value. If this node is a leaf, return whether tmp
is equal to sum
. Finally, recursively traverse the tree in depth. By using short-circuit evaluation, if the left subtree is true, the right subtree will not be recursively computed, and if the right subtree is true, the upper-level recursive computation will be directly returned. This can achieve the computation of path sum.