给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。
    例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
    对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
    返回这些数字之和。题目数据保证答案是一个 32 位 整数。

    示例 1:
    输入:root = [1,0,1,0,1,0,1]

    1. 1
    2. / \
    3. 0 1
    4. / \ / \
    5. 0 1 0 1

    输出:22
    解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

    示例 2:
    输入:root = [0]
    输出:0

    需要先计算所有的路径,然后依次将路径转二进制,最后进行求和

    LeetCode 257. 查找二叉树所有的路径:

    1. private List<String> binaryTreePaths(TreeNode node, String path, List<String> result) {
    2. if (node == null) {
    3. return result;
    4. }
    5. path = path + node.val;
    6. if (node.left == null && node.right == null) {
    7. result.add(path);
    8. return result;
    9. }
    10. path = path + "->";
    11. binaryTreePaths(node.left, path, result);
    12. binaryTreePaths(node.right, path, result);
    13. return result;
    14. }

    只要去除连接符号,即可得到二进制字符串

    1. private List<String> binaryTreePaths(TreeNode node, String path, List<String> result) {
    2. if (node == null) {
    3. return result;
    4. }
    5. path = path + node.val;
    6. if (node.left == null && node.right == null) {
    7. result.add(path);
    8. return result;
    9. }
    10. binaryTreePaths(node.left, path, result);
    11. binaryTreePaths(node.right, path, result);
    12. return result;
    13. }

    得到二进制字符串后,再转换为十进制并求和即可

    1. public int sumRootToLeaf(TreeNode root) {
    2. List<String> result = new ArrayList<>();
    3. binaryTreePaths(root, "", result);
    4. int sum = 0;
    5. for (String value: result) {
    6. sum = sum + Integer.valueOf(value, 2);
    7. }
    8. return sum;
    9. }
    10. private List<String> binaryTreePaths(TreeNode node, String path, List<String> result) {
    11. if (node == null) {
    12. return result;
    13. }
    14. path = path + node.val;
    15. if (node.left == null && node.right == null) {
    16. result.add(path);
    17. return result;
    18. }
    19. binaryTreePaths(node.left, path, result);
    20. binaryTreePaths(node.right, path, result);
    21. return result;
    22. }

    直接求和

    1. int sum = 0;
    2. public int sumRootToLeaf(TreeNode root) {
    3. binaryTreePaths(root, "");
    4. return sum;
    5. }
    6. private void binaryTreePaths(TreeNode node, String path) {
    7. if (node == null) {
    8. return;
    9. }
    10. path = path + node.val;
    11. if (node.left == null && node.right == null) {
    12. sum = sum + Integer.valueOf(path, 2);
    13. return;
    14. }
    15. binaryTreePaths(node.left, path);
    16. binaryTreePaths(node.right, path);
    17. }