leetcode -- 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
.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int sumNumbers(TreeNode root) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 if(root == null){ 15 return 0; 16 } 17 ArrayList<String> result = new ArrayList<String>(); 18 StringBuilder sb = new StringBuilder(); 19 int sum = 0; 20 dfs(root, sb, result); 21 for(int i = 0; i < result.size(); i++){ 22 sum += Integer.parseInt(result.get(i)); 23 } 24 return sum; 25 } 26 27 public void dfs(TreeNode root, StringBuilder sb, ArrayList<String> result){ 28 if(root.left == null && root.right == null){ 29 sb.append(root.val); 30 result.add(sb.toString()); 31 sb.deleteCharAt(sb.length() - 1); 32 return; 33 } 34 sb.append(root.val); 35 if(root.left != null){ 36 //sb.append(root.left.val); 37 dfs(root.left, sb, result); 38 //sb.deleteCharAt(sb.length() - 1); 39 } 40 if(root.right != null){ 41 //sb.append(root.right.val); 42 dfs(root.right, sb, result); 43 //sb.deleteCharAt(sb.length() - 1); 44 } 45 sb.deleteCharAt(sb.length() - 1); 46 } 47 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2012-08-12 本周小结
2012-08-12 ubuntu 手动设置DNS服务器,重启后不能上网