leetcode:437. Path Sum III

Source: Internet
Author: User

You is given a binary tree in which each node contains an integer value.

Find the number of paths this sum to a given value.

The path does not need-to-start or end at the root or a leaf, but it must go downwards (traveling with from parent nodes T o child nodes).

The tree has no more than nodes and the values is in the range-1,000,000 to 1,000,000.

Example:

root = [Ten,5,-3,3,2,NULL, One,3,-2,NULL,1], sum =8      Ten/      5-3/ \      3   2    One/ \   3-2   1Return3. The paths, sum to8is :1.5-32.5-2-13. -3- One

Given a binary tree, find the path and the number of paths equal to sum. The path here refers to the path from the parent node to the child node, not necessarily from the root node to the leaf node. Think of depth-first search immediately, but note that the path does not necessarily start at the root node. So for a parent node, the path on the path that meets the requirements of the problem should include the path in the left and right subtrees and the path to sum in addition to the path in the left and right subtree and the path to Sum-root->val.

/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public:    intPathsum (treenode* root,intsum) {        if(!root)return 0; returnPathsum (root->left,sum) +pathsum (root->right,sum) +Pathsumroot (root,sum); }        intPathsumroot (treenode* root,intsum) {        if(!root)return 0; intCount= (sum==root->val?1:0); returnPathsumroot (Root->left,sum-root->val) + pathsumroot (root->right,sum-root->val) +count; }};

leetcode:437. Path Sum III

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.