Leetcode 129. Sum Root to Leaf Numbers

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.

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.

題意:一個二叉樹每個節(jié)點是一個0-9的數(shù)字,從根節(jié)點到葉子節(jié)點可以看做是一個數(shù)字,求所有數(shù)字的和。

思路:用深度優(yōu)先搜索求出每個根節(jié)點到葉子節(jié)點代表的數(shù)字,最后求和即可。

public int res = 0;

public int sumNumbers(TreeNode root) {
    if (root == null) {
        return res;
    }

    dfs(root, 0);

    return res;
}

private void dfs(TreeNode node, int curSum) {
    curSum = curSum * 10 + node.val;

    if (node.left == null && node.right == null) {
        res += curSum;
        return;
    }

    if (node.left != null) {
        dfs(node.left, curSum);
    }

    if (node.right != null) {
        dfs(node.right, curSum);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容