標籤: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