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 123
.
Find The total sum of all root-to-leaf numbers.
For example,
1 / 2 3
The Root-to-leaf Path1->2
Represents the number12
.
The Root-to-leaf Path1->3
Represents the number13
.
Return the sum = + = 25
.
Problem Solving Ideas:
A binary tree node value is composed of 0~9 numbers, from the root node to each leaf node is composed of an integer, the root node at the highest level, the leaf node in the lowest bit. Now we're going to add the value of all these shaping numbers together.
Method One: The most straightforward method is to traverse the two-fork tree horizontally, and set the value of each node to the parent node *10+ the node Val. Finally, we simply add the Val value of the leaf node. The code is as follows:
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {Public:int sumnumbers (treenode* root) {if (root==null) return 0; if (root->left==null&&root->right==null) return root->val; int sum=0; treenode* R=root; deque<treenode* > St; St.push_back (R); deque<treenode* >st1; while (!st.empty ()) {treenode* node=st.front (); St.pop_front (); if (node->left) {node->left->val+=node->val*10; St1.push_back (Node->left); if (node->left->left==null&&node->left->right==null) sum+=node->left->val; } if (node->right) {node->right->val+=node->val*10; St1. push_back (Node->right); if (node->right->left==null&&node->right->right==null) sum+=node->right->val; } if (St.empty ()) {st=st1; St1.clear (); }} return sum; }};
Method Two:
Using recursion, int sumval (treenode* root,int c) where root refers to a node in the tree, C refers to the Val value of the parent node of this node. Returns the sum value of this node to the leaf node.
Class Solution {public: int sumval (treenode* root,int c) { int val=0; if (root->left==null&&root->right==null) return c*10+root->val; if (root->left!=null) val+=sumval (root->left,c*10+root->val); if (root->right!=null) val+=sumval (root->right,c*10+root->val); return val; } int sumnumbers (treenode* root) { if (root==null) return 0; if (root->left==null&&root->right==null) return root->val; Return Sumval (root,0); };
Sum Root to Leaf Numbers