Sum Root to Leaf Numbers--leetcode

Source: Internet
Author: User

Topic:

Given a binary tree containing digits from only 0-9 , each root-to-leaf path could represent a number.

an example is the root-to-leaf path 1->2->3  which represents the Number 

Find The total sum of all root-to-leaf numbers.

For example,

    1   /   2   3

The Root-to-leaf Path1->2Represents the number12.
The Root-to-leaf Path1->3Represents the number13.

Return the sum = + = 25 .

Idea: If you know the number on the path from the root node to all the leaf nodes, and then convert the path to an integer, add all the integer of the path conversion, which is the result of the request.

void Helper_leaf (bintree* root,vector<int>& path,int& sum) {if (root = NULL) return;p ath.push_back (root- >value); if (root->left = = NULL && Root->right = = null) {int tmp=0;for (int i=0;i<path.size (); i++) tmp = tmp*10 + path[i];sum + = tmp;//cout<< "tmp is" <<tmp<<endl; return;} Helper_leaf (root->left,path,sum); Helper_leaf (root->right,path,sum);p ath.pop_back ();} int roottoleaf (bintree* root) {if (root = NULL) return 0;vector<int> path;int sum=0;helper_leaf (root,path,sum); return sum;}




Sum Root to Leaf Numbers--leetcode

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.