二叉树根到叶子所有数字的和

图示

代码

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
56
57
58
59
60
import java.util.ArrayList;
import java.util.List;

class Node {
int val;
Node left;
Node right;

public Node(int val) {
this.val = val;
}
}

public class Main {
private static List<Integer> list;

public static void main(String[] args) {
// 叶子节点
Node n1 = new Node(1);
Node n2 = new Node(5);
Node n3 = new Node(1);
// 根节点
Node root = new Node(1);
// 其他节点
Node o1 = new Node(2);
Node o2 = new Node(2);
// 组装
root.left = o1;
o1.left = n1;
o1.right = n2;
root.right = o2;
o2.right = n3;
// 计算结果
list = new ArrayList<>();
int result = findBinaryTreeSum(root);
System.out.println(result);
}

private static int findBinaryTreeSum(Node root) {
if (root == null) return 0;
list.add(root.val);
if (root.left == null && root.right == null) { // 到达叶子节点,开始计算
int num = sumList(list);
list.remove(list.size() - 1);
return num;
} else {
int subSum = findBinaryTreeSum(root.left) + findBinaryTreeSum(root.right);
list.remove(list.size() - 1);
return subSum;
}
}

private static int sumList(List<Integer> list) {
int num = 0;
for (Integer integer : list) {
num = num * 10 + integer;
}
return num;
}
}

二叉树根到叶子所有数字的和
https://blog.wangxk.cc/2021/04/28/二叉树根到叶子所有数字的和/
作者
Mike
发布于
2021年4月28日
许可协议