Leetcode Note: Sum Root to Leaf Numbers
I. Description
Given a binary tree containing digits from 0-9 only, each root-to-leaf path cocould 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->2Represents the number12.
The root-to-leaf path1->3Represents the number13.
Returnsum = 12 + 13 = 25.
Ii. Question Analysis
This question is just a binary tree deep Priority Search question. When the leaf node points, the node values from the root to the leaf node path constitute a decimal number, in essence, it is still a deep-first search question.
Iii. Sample Code
#include
struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{ void sumNumbers(TreeNode*root, int &Result, int &TmpResult) { if (!root) { return; } // update the TmpResult TmpResult = TmpResult * 10 + root->val; if (!root->left && !root->right) { Result += TmpResult; } if (root->left) { sumNumbers(root->left, Result, TmpResult); } if (root->right) { sumNumbers(root->right, Result, TmpResult); } // restore the TmpResult; TmpResult = (TmpResult - root->val) / 10; }public: int sumNumbers(TreeNode* root) { int Result = 0; int TmpResult = 0; sumNumbers(root, Result, TmpResult); return Result; }};
Iv. Summary
This question is a problem of deformation of binary tree deep priority search. It is the recursive traversal of binary tree, but it is just a different method.