[LeetCode][Java] Sum Root to Leaf Numbers

來源:互聯網
上載者:User

標籤:leetcode   java   sum root to leaf num   

題目:

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.

題意:

給定一棵二叉樹,僅僅包含0-9的數字元素,每一條從根節點到葉子節點的路徑都可以代表一個數.

舉個例子一條從根節點到葉子節點的路徑為1->2->3代表數為123.

找出所有的從根到葉子節點路徑中所表示的數的和。

比如給定:

    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.

演算法分析:

通過遞迴,思路比較清晰,主要就是考慮遞迴條件和結束條件。直接看代碼,比較好理解。

AC代碼:

<span style="font-family:Microsoft YaHei;font-size:12px;">/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */ //又是遞迴public class Solution {    int sum = 0;    public int sumNumbers(TreeNode root)     {        if (root == null) return 0;        run(root, 0);        return sum;    }    public void run(TreeNode root, int num)     {        num = 10 * num + root.val;        if (root.left == null && root.right == null)             sum += num;        if (root.left != null)             run(root.left, num);        if (root.right != null)            run(root.right, num);    }}</span>

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Sum Root to Leaf Numbers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.