原题链接:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
1. 题目介绍
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Return the sum of these numbers.
给出一个二叉树,每个节点的值都是0或者1。
每个从根节点出发,到叶子节点结束的路径都代表了一个二进制的数字。比如路径是 0 -> 1 -> 1 -> 0 -> 1 时,所代表的二进制数是01101,也就是13
找出所有的从根节点到叶子节点的路径,计算所代表的二进制数字的和。
Example 1:
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Note:
The number of nodes in the tree is between 1 and 1000.
node.val is 0 or 1.
The answer will not exceed 231 - 1.
节点的总数是1到1000
每个节点的val值只有0或者1
求和的结果不会超过 231 - 1.
2. 解题思路
使用深度优先搜索的顺序遍历全部的节点。一边遍历,一边记录总和,当到达叶子节点的时候,返回总和。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
if(root == null){
return 0;
}
return dfs(root,0);
}
public int dfs(TreeNode node , int total){
if(node == null){
return 0;
}
total += node.val;
if(node.left == null && node.right == null){
return total;
}
return dfs(node.left, total*2) + dfs(node.right, total*2);
}
}
当然,也可以使用 List 来记录所有经过的节点的值,在到达叶子节点的时候,再遍历 List 中所有经过节点的 val 值,求得一个路径对应的数是多少。在计算完每一个路径的数之后,将其加到总和里面去。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> bits;
int sum = 0;
public int sumRootToLeaf(TreeNode root) {
if(root == null){
return 0;
}
bits = new ArrayList<>();
dfs(root);
return sum;
}
public void dfs(TreeNode node){
if(node == null){
return;
}
bits.add(node.val);
if(node.left == null && node.right == null){
sum += listToNum(bits);
}
dfs(node.left);
dfs(node.right);
bits.remove(bits.size()-1);
}
public int listToNum(List<Integer> l){
int ans = 0;
int n = l.size();
for(int i = 0 ;i < n-1 ;i++){
ans += l.get(i);
ans <<= 1;
}
ans += l.get(n-1);
return ans;
}
}