Leetcode (:P) Ath Sum

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.