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 and
sum = 22
,
5 / 4 8 / / / 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
ways to search for branches
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: bool Findpath (treenode* root, int nowsum,const int sum) { Nowsum + = root->val;/ /Current value //If it is already a leaf node and is equal, return True if (!root->left &&!root->right && nowsum = = sum) return true; BOOL Found_left = false; BOOL Found_right = false; if (root->left)//left dial hand tree is not empty, then search in the left subtree found_left = Findpath (root->left, nowsum, sum); if (!found_left && root->right)//If Zuozi not found, search in right subtree found_right = Findpath (root->right, nowsum, sum ); return Found_left | | found_right;//returns True } bool Haspathsum (treenode* root, int sum) { if (root = NULL) return as long as it is found in one branch false; Findpath (root, 0, sum); };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode (:P) Ath Sum