LeetCode 1022 Sum of Root To Leaf Binary Numbers

题意

给予一颗二叉树,每个节点的值只有 0 和 1, 每个根到叶子节点的路径都是一个有效的二进制树, 如: 0 -> 1 -> 1 -> 0 -> 1, 那么用二进制表示就是 01101, 对应十进制为 13.

对于树中的所有叶子节点, 请返回根节点到这些叶子节点的路径所代表的二进制值的和.

例 :

1
2
3
4
5
6
7
8
9
10
给予树:

1
/ \
0 1
/ \ / \
0 1 0 1

返回: 22.
说明: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

解法

采用深度优先遍历, 从跟节点开始, 到下一层的时候, 将父节点的值向左移动一位, 再加上当前节点的值, 直到根节点为止.

如上图中, 1 -> 0 -> 0 这个路径, 从根节点 1 开始, 到第二层, 对 1 左移一位 i = 1 << 1, 等于 10, 再加上当前节点的值 0 等于 10, 再到下一层, 向左移动一位 i = 10 << 1, 等于 100.

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {

int result = 0;

public int sumRootToLeaf(TreeNode root) {
dfs(root, 0);
return result;
}

public void dfs(TreeNode node, int currentVal) {
if (node != null) {
currentVal <<= 1;
currentVal += node.val;
if (node.left == null && node.right == null) {
result += currentVal;
}
dfs(node.left, currentVal);
dfs(node.right, currentVal);
}
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Root To Leaf Binary Numbers.
Memory Usage: 35.4 MB, less than 100.00% of Java online submissions for Sum of Root To Leaf Binary Numbers.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-1022/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!