leetcode --sum-root-to-leaf-numbers

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
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 = 12 + 13 =25.


思路:本題可以按照先序遍歷來求和,對于每個結(jié)點,采用 temp = value* 10 + node->val來更新值。注意先序遍歷的寫法,不要多考慮情況,一開始我加的判斷太多了,其實根本不需要,只需要判斷傳入的Node是否為空即可?。《恍枰A先做判斷。

代碼如下:

/**
 * Definition for binary tree
 * 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 == nullptr) return 0;
        return sum(root,0);
    }
    int sum(TreeNode *root ,int value) {
        if(root == nullptr) 
            return 0;
        int temp = value * 10 + root->val;
        if(root->left == nullptr && root->right == nullptr) return temp;
        return sum(root->right,temp) + sum(root->left,temp);
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • **Question: Given a binary tree containing digits from 0-...
    Richardo92閱讀 476評論 1 2
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • 目錄 簡書的 markdown 都不支持 [TOC] 語法……我就不貼目錄了。下面按照類別,列出了29道關(guān)于二叉樹...
    被稱為L的男人閱讀 3,439評論 0 8
  • 當我們老了 歲月把我們的青絲 換成了白發(fā) 年輕飛揚的意氣風發(fā) 換成了沉穩(wěn)寧靜 濃情蜜意刻畫出 愛情的故事 牽手相伴...
    郭相麟閱讀 215評論 0 0
  • 或許分離, 會是另一種回歸。 回家的路途很近,坐趟剛開通的20分鐘的地鐵就可以到達當?shù)氐幕疖囌?,再坐趟一個半左右時...
    魔導閱讀 290評論 3 0

友情鏈接更多精彩內(nèi)容