求根到叶子节点数字之和
前序遍历+判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
//List<String> res = new LinkedList<>();
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
preOrder(root,"");
//for(int i=0;i<res.size();i++)
//System.out.print(res.get(i)+" ");
return res;
}
public void preOrder(TreeNode root,String tmp){
if(root == null) return;
tmp += root.val+"";
if(root.left == null && root.right == null){
res += Integer.parseInt(tmp);
//res.add(tmp);
tmp = tmp.substring(0,tmp.length()-1);
return;
}
preOrder(root.left,tmp);
preOrder(root.right,tmp);
}
}
不一样的烟火
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步