Question
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.
For 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 path5->4->11->2Which sum is 22.
Answer
Recursive Solutions
/*** Definition for binary tree * Public class treenode {* int val; * treenode left; * treenode right; * treenode (int x) {val = x ;} *} */public class solution {public Boolean haspathsum (treenode root, int sum) {If (root = NULL) {return false;} If (root. left = NULL & root. right = NULL & sum-root.val = 0) {// note that there must be a path from the root node to the leaf node at the same time, only the root node is not the required return true ;} boolean BL = false; Boolean BR = false; If (root. left ! = NULL) {BL = haspathsum (root. Left, sum-root.val);} If (root. Right! = NULL) {BR = haspathsum (root. Right, sum-root.val);} return BL | BR ;}}
--- EOF ---