Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.
For example:
Given the below binary tree sum = 22 and,
5 / 4 8 / / / 4 / \ 7 2 1
structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: BOOLHaspathsum (TreeNode *root,intsum) { //Start Typing your/C + + solution below//Do not write int main () function if(!root)return false; Flag=false; Target=sum; Preorder (Root,0); returnFlag; } voidPreorder (treenode* node,intsum) {Sum= Node->val + sum;//before recursion, add the current node if(node->Left ) {Preorder (node-left,sum); } if(node->Right ) {Preorder (node-right,sum); } if(!node->left &&!node->right && sum = = target)//recursive end condition: to the leaf node{flag=true; } }Private: BOOLFlag; inttarget;};
The. Path Sum (Tree; DFS)