[LeetCode] 129. Sum Root to Leaf Numbers
You are given the root
of a binary tree containing digits from 0
to 9
only.
Each root-to-leaf path in the tree represents a number.
- For example, the root-to-leaf path
1 -> 2 -> 3
represents the number123
.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
A leaf node is a node with no children.
Example 1:
Input: root = [1,2,3] Output: 25 Explanation: The root-to-leaf path1->2
represents the number12
. The root-to-leaf path1->3
represents the number13
. Therefore, sum = 12 + 13 =25
.
Example 2:
Input: root = [4,9,0,5,1] Output: 1026 Explanation: The root-to-leaf path4->9->5
represents the number 495. The root-to-leaf path4->9->1
represents the number 491. The root-to-leaf path4->0
represents the number 40. Therefore, sum = 495 + 491 + 40 =1026
.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. 0 <= Node.val <= 9
- The depth of the tree will not exceed
10
.
求根到叶子节点数字之和。
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
每条从根节点到叶节点的路径都代表一个数字:例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
计算从根节点到叶节点生成的 所有数字之和 。叶节点 是指没有子节点的节点。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-root-to-leaf-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是前序遍历。记录一个变量 sum 存之前所有的加和,当遍历到当前节点的时候,sum *= 10 再加当前的节点值 cur.val。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 int res = 0; 18 19 public int sumNumbers(TreeNode root) { 20 helper(root, 0); 21 return res; 22 } 23 24 private void helper(TreeNode root, int sum) { 25 if (root == null) { 26 return; 27 } 28 sum = sum * 10 + root.val; 29 if (root.left == null && root.right == null) { 30 res += sum; 31 return; 32 } 33 helper(root.left, sum); 34 helper(root.right, sum); 35 } 36 }
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {number} 4 */ 5 var sumNumbers = function (root) { 6 if (root == null) { 7 return 0; 8 } 9 var total = 0; 10 helper(root, 0); 11 return total; 12 13 function helper(root, sum) { 14 if (root == null) { 15 return; 16 } 17 sum = sum * 10 + root.val; 18 if (root.left == null && root.right == null) { 19 total += sum; 20 return; 21 } 22 helper(root.left, sum); 23 helper(root.right, sum); 24 } 25 };
相关题目