Sum of Root To Leaf Binary Numbers
在树上找到binary,加起来。难点是怎么表示binary,我看答案好多用int乘来乘去,我这里选择string表示。使用Integer的parseString比较方便。而且答案易懂。
class Solution {
int sum = 0;
public int sumRootToLeaf(TreeNode root) {
solve(root,"");
return sum;
}
private void solve(TreeNode root, String s) {
if(root.left == null && root.right == null) {
sum += toInt(s+root.val);
}
if(root.left != null)
solve(root.left, s+root.val);
if(root.right != null)
solve(root.right, s+root.val);
}
private int toInt(String s) {
return Integer.parseInt(s,2);
}
}