LC.P1022[从根到叶的二进制数之和]

方法一:DFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}

private int dfs(TreeNode root, int x) {
if (root == null) return 0;
x = (x << 1) + root.val;
if (root.left == null && root.right == null) {
return x;
}
int left = dfs(root.left, x);
int right = dfs(root.right, x);
return left + right;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:BFS

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
int ans = 0;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur.left != null) {
cur.left.val = (cur.val << 1) + cur.left.val;
queue.offer(cur.left);
}
if (cur.right != null) {
cur.right.val = (cur.val << 1) + cur.right.val;
queue.offer(cur.right);
}
if (cur.left == null && cur.right == null) {
ans += cur.val;
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$