1. 问题描述:
Given a binary containing digits from 0-9 only, each root-to-leaf path path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123
Find the total sum of all root-to-leaf numbers.
For example,
1
2 3
The root-to-leaf path1->2represents the numbe 12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 = 25
2. 题目的意思大概是:从根节点到叶子节点的路径中,把其中的路径上的数字拼接成一个字符串形成一个数字,需要把这些所有路径上的字符串数字加起来
思路是:使用深搜的办法即可轻松解决,递归搜索左子树与右子树,当搜索到叶子节点的时候表示路径结束应该把当前形成的字符串加入到List中,等到所有的路径搜索完毕,遍历List将数字字符串转化成数字然后加起来即可
代码如下:
import java.util.ArrayList;
import java.util.List;
public class Main {
//路径数字串之和
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
TreeNode<Integer> root = new TreeNode<Integer>(1);
TreeNode<Integer> l = new TreeNode<Integer>(2);
TreeNode<Integer> ll = new TreeNode<Integer>(4);
TreeNode<Integer> lr = new TreeNode<Integer>(7);
TreeNode<Integer> r = new TreeNode<Integer>(3);
TreeNode<Integer> rr = new TreeNode<Integer>(5);
TreeNode<Integer> rl = new TreeNode<Integer>(8);
root.left = l;
root.right = r;
l.left = ll;
l.right = lr;
r.right = rr;
r.left = rl;
int sum = setSums(root);
System.out.println(sum);
}
static void solve(String str, TreeNode node){
str += node.val;
if(node.left == null && node.right == null){
list.add(str);
return;
}
if(node.left != null){
solve(str, node.left);
}
if(node.right != null){
solve(str, node.right);
}
}
static int setSums(TreeNode root){
if(root == null) return 0;
solve("", root);
int sum = 0;
for(int i = 0; i < list.size(); i++){
sum += Integer.parseInt(list.get(i));
}
return sum;
}
}
TreeNode节点的定义如下:
public class TreeNode<T> {
public T val;
public TreeNode<T> left = null;
public TreeNode<T> right = null;
public TreeNode<T> parent = null;
public TreeNode(T val) {
this.val = val;
}
@Override
public String toString() {
return "TreeNode [val=" + val + "]";
}
}