404. Sum of Left Leaves solution records, 404 leaves

Source: Internet
Author: User

404. Sum of Left Leaves solution records, 404 leaves
Description:

Find the sum of all left leaves in a given binary tree.

Example:

 

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

 

Solution:

Use recursion to traverse the binary tree, determine whether it is the left leaf of the last branch, and then add the left leaf of all the last branch (do not forget to consider the case of Null Pointer)

Code:

 

1/** 2 * Definition for a binary tree node. 3 * struct TreeNode {4 * int val; 5 * struct TreeNode * left; 6 * struct TreeNode * right; 7 *}; 8 */9 int sumOfLeftLeaves (struct TreeNode * root) {10 if (! Root) 11 // when the input is null, 12 {13 return 0; 14} 15 int leftLeavesSum = 0; 16 if (root-> left) 17 {18 if (! Root-> left &&! Root-> left-> right) 19 // the condition for the end, that is, when the left leaf of the Branch is 20 {21 leftLeavesSum + = root-> left-> val; 22} 23 else24 {25 leftLeavesSum + = sumOfLeftLeaves (root-> left); 26} 27} 28 if (root-> right) 29 {30 leftLeavesSum + = sumOfLeftLeaves (root-> right); 31} 32 return leftLeavesSum; 33}

 

Solution gains:

The use of the C-language linked list is still not good enough, and more exercises are required.

 

Related Article

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.