国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] Sum Root to Leaf Numbers

魏明 / 952人閱讀

Problem

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: A leaf is a node with no children.

Example

Input: [1,2,3]

    1
   / 
  2   3

Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:

Input: [4,9,0,5,1]

    4
   / 
  9   0
 / 
5   1

Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

Solution
class Solution {
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        return sum(root, 0);
    }
    private int sum(TreeNode root, int cur) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return cur*10+root.val;
        return sum(root.left, cur*10+root.val)+sum(root.right, cur*10+root.val);
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/71120.html

相關文章

  • [Leetcode-Tree] Sum Root to Leaf Numbers

    摘要:解題思路本題要求所有從根結點到葉子節點的路徑和,我們用遞歸實現。結束條件當遇到葉子節點時,直接結束,返回計算好的如果遇到空節點,則返回數值。 Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numbe...

    BigNerdCoding 評論0 收藏0
  • [Leetcode] Sum Root to Leaf Numbers 累加葉子節點

    摘要:遞歸法復雜度時間空間遞歸棧空間思路簡單的二叉樹遍歷,遍歷時將自身的數值加入子節點。一旦遍歷到葉子節點便將該葉子結點的值加入結果中。 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...

    wean 評論0 收藏0
  • [LeetCode] Path Sum (I & II & III)

    摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...

    張金寶 評論0 收藏0
  • [Leetcode-Tree] Path Sum I II III

    摘要:解題思路利用遞歸,對于每個根節點,只要左子樹和右子樹中有一個滿足,就返回每次訪問一個節點,就將該節點的作為新的進行下一層的判斷。代碼解題思路本題的不同點是可以不從開始,不到結束。代碼當前節點開始當前節點左節點開始當前節點右節點開始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...

    notebin 評論0 收藏0
  • LeetCode 之 JavaScript 解答第112題 —— 路徑總和(Path Sum

    摘要:小鹿題目路徑總和給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等于目標和。說明葉子節點是指沒有子節點的節點。 Time:2019/4/26Title: Path SumDifficulty: EasyAuthor: 小鹿 題目:Path Sum(路徑總和) Given a binary tree and a sum, determin...

    lylwyy2016 評論0 收藏0

發表評論

0條評論

魏明

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<