Path sum path and

Source: Internet
Author: User

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 andsum = 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.

 

This binary tree path requires the deep-Priority Algorithm DFS to traverse each complete path, that is, to recursively locate the Left and Right subnodes of the subnode, the parameters that call recursive functions are only the current node and sum value. First, if an empty node is input, false is returned directly. If only one root node is input, check whether the value of the current root node is the same as that of the sum parameter, if the values are the same, true is returned; otherwise, false is returned. This condition is also a recursive termination condition. Next we will start recursion. Since the return value of the function is true/false, We Can recursively combine the two directions at the same time, and use or | link in the middle, as long as one is true, the entire result is true. When recursion is performed on left and right nodes, the sum value is the original sum value minus the current node value. The Code is as follows:

 

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool hasPathSum(TreeNode *root, int sum) {        if (root == NULL) return false;        if (root->left == NULL && root->right == NULL && root->val == sum ) return true;        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);    }};

 

Path sum path and

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.