Description:
Given a binary tree containing digits from 0-9
only,
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.
Note:
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
Solution:
Analysis and Thinking:
題目要求求出輸入二叉樹的所有路徑代表的數字的相加值,其中每一條路徑都是根節點到葉節點的,且按順序組合起來代表一個數字,每一個節點的數字爲0-9。可利用遞歸法實現,因爲輸出是樹的從根到葉的節點的所有路徑相加結果,因此,遞歸條件可設爲當前記錄的Sum值x10後加上當前遍歷的節點的值,然後再把更新的sum傳給下一個遞歸過程。結束條件可設爲,若遍歷的當前節點爲葉子,將目前sum值x10加上葉子值,加到最終結果記錄變量當中,最終我們需要把左右子樹的和相加。
Steps:
1.判斷當前節點是否爲空,若是,返回0
2.判斷當前節點是否爲葉節點,若是,將遞歸累加和結果x10後加上葉子值,返回
3.如果當前遍歷節點爲非葉子節點,則遍歷其左右子樹,並把其左右子樹相加,當做最終和值
Codes:
class Solution
{
public:
int sumNumbers(TreeNode *root)
{
return sumNumbers_2(root,0)
}
int sumNumbers_2(TreeNode* root,int record)
{
if(root==NULL) return 0;//特殊情況,若當前節點爲空,返回0
if(root->right==NULL&&root->left==NULL) //特殊情況,如果當前值爲葉子節點
{
return record*10+root->value;
}
return sumNumbers_2(root->left,record*10+root->value)+sumNumbers_2(root->right,record*10+root->value) //非葉子節點,將左右子樹結果相加
}
};
Results: