Leetcode: Path_Sum

Source: Internet
Author: User

I. Question

We will give you a binary tree and an integer to determine whether there is a path from the root node to the leaf node in the tree so that the value on this path is the sum of this integer.

Example: binary tree and value 22

                 5

/\

4 8

//\

11 13 4

/\\

7 2 1

Path: 5-4-11-+ 4 + 11 + 2 = 22

II. Analysis

First of all, what makes me feel the worst about this question?

1> value determination (PS: even if the root node is not 0, the result may be 0. Do not forget that the value can be negative or zero)

2> If sum = 0 and root node is NULL, the result is true or false. It turns out that if the root node is NULL, the result is false;

Next, we can continue to use recursion by using sum to subtract the value of the current left or right subtree and call this function again.

 

/*** 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 & sum = root-> val) return true; return hasPathSum (root-> left, sum-root-> val) | hasPathSum (root-> right, sum-root-> val );}};


Leetcode: Path_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.