|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=1022 lang=java |
| 3 | + * |
| 4 | + * [1022] Sum of Root To Leaf Binary Numbers |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (65.39%) |
| 10 | + * Likes: 380 |
| 11 | + * Dislikes: 66 |
| 12 | + * Total Accepted: 33.7K |
| 13 | + * Total Submissions: 51.6K |
| 14 | + * Testcase Example: '[1,0,1,0,1,0,1]' |
| 15 | + * |
| 16 | + * Given a binary tree, each node has value 0 or 1. Each root-to-leaf path |
| 17 | + * represents a binary number starting with the most significant bit. For |
| 18 | + * example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent |
| 19 | + * 01101 in binary, which is 13. |
| 20 | + * |
| 21 | + * For all leaves in the tree, consider the numbers represented by the path |
| 22 | + * from the root to that leaf. |
| 23 | + * |
| 24 | + * Return the sum of these numbers. |
| 25 | + * |
| 26 | + * |
| 27 | + * |
| 28 | + * Example 1: |
| 29 | + * |
| 30 | + * |
| 31 | + * |
| 32 | + * |
| 33 | + * Input: [1,0,1,0,1,0,1] |
| 34 | + * Output: 22 |
| 35 | + * Explanation: (100) + (101) + (110) + (111) = 4 +たす 5 +たす 6 +たす 7 =わ 22 |
| 36 | + * |
| 37 | + * |
| 38 | + * |
| 39 | + * |
| 40 | + * Note: |
| 41 | + * |
| 42 | + * |
| 43 | + * The number of nodes in the tree is between 1 and 1000. |
| 44 | + * node.val is 0 or 1. |
| 45 | + * The answer will not exceed 2^31 - 1. |
| 46 | + * |
| 47 | + * |
| 48 | + */ |
| 49 | + |
| 50 | +// @lc code=start |
| 51 | +/** |
| 52 | + * Definition for a binary tree node. |
| 53 | + * public class TreeNode { |
| 54 | + * int val; |
| 55 | + * TreeNode left; |
| 56 | + * TreeNode right; |
| 57 | + * TreeNode(int x) { val = x; } |
| 58 | + * } |
| 59 | + */ |
| 60 | +class Solution { |
| 61 | + int callme(int cur, TreeNode root){ |
| 62 | + if(root == null) |
| 63 | + return 0; |
| 64 | + cur = cur*2 + root.val; |
| 65 | + if(root.left == null && root.right == null) |
| 66 | + return cur; |
| 67 | + return callme(cur, root.left) + callme(cur, root.right); |
| 68 | + } |
| 69 | + public int sumRootToLeaf(TreeNode root) { |
| 70 | + return callme(0, root); |
| 71 | + } |
| 72 | +} |
| 73 | +// @lc code=end |
0 commit comments