Title Description
Given a binary tree and a destination and determines whether the root node to the leaf node in the tree path exists, all the nodes on this route, and equal to the target value is added.
Description: leaf node is a node has no child nodes.
Ideas analysis
To analyze what conditions recursion is terminated? Recursive to be what action? Recursive want to return to what information?
Termination condition: the node is null
Recursive operation: sum value by subtracting the current node and the current node is a leaf returns true when the sum is 0
Recursive returned was: Is there a qualified path to the left and right subtree
Code
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
sum -= root.val;
if (sum == 0 && root.left == null && root.right == null) {
return true;
}
return hasPathSum(root.left, sum) ||
hasPathSum(root.right, sum);
}