パスとツリーleecode
4342 ワード
テーマは難しくなく、すぐにacして、純粋に手触りに頼っています.https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
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 private int sum=0;
12 public int sumNumbers(TreeNode root) {
13 if(root==null) return 0;
14
15
16
17 sum(root,""+root.val);
18 return sum;
19
20 }
21 public void sum(TreeNode root,String s)
22 {
23
24 if(root.left==null&&root.right==null)
25 {
26 sum+=Integer.parseInt(s);
27 }
28 else
29 {
30 if(root.left!=null) sum(root.left,s+root.left.val);
31 if(root.right!=null) sum(root.right,s+root.right.val);
32
33
34
35 }
36
37
38
39 }
40
41 }