-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT22.java
More file actions
55 lines (47 loc) · 1.32 KB
/
T22.java
File metadata and controls
55 lines (47 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @author aliyang
* @date 18-6-1 下午6:56
* sum-root-to-leaf-numbers:我的解法
* 思路:使用递归
* 别人思想改进:不用字符串,直接用数字,每下一层那么乘10
*/
public class T22 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
int sum=0;
public int sumNumbers(TreeNode root) {
if (root==null)
return 0;
StringBuilder cur=new StringBuilder();
traverse(root,cur);
return sum;
}
private void traverse(TreeNode root,StringBuilder cur){
cur.append(root.val);
if (root.left==null&&root.right==null){
if (!cur.equals(""))
sum+=Integer.valueOf(cur.toString());
return;
}
if (root.left!=null){
traverse(root.left,cur);
cur.deleteCharAt(cur.length()-1);
}
if (root.right!=null){
traverse(root.right,cur);
cur.deleteCharAt(cur.length()-1);
}
}
public static void main(String[] args){
T22 t=new T22();
TreeNode root=new TreeNode(1);
TreeNode realRoot=root;
// root.left=new TreeNode(2);
root.right=new TreeNode(5);
System.out.println(t.sumNumbers(root));
}
}