路径数字串之和
/*Given a binary tree containing digits from0-9only,
each root-to-leaf 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 number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.*/
package _8题;
import java.util.ArrayList;
import java.util.List;
public class sumNumbers {
public int SumNumbers(TreeNode<Integer>root) {
if(root== null)return 0;
f("",root); //开始递归
int sum=0;
for(int i=0;i<list.size();i++) {
sum+=Integer.parseInt(list.get(i));//拆箱
}
return sum;
}
private void f(String pre, TreeNode<Integer> node) {
// TODO Auto-generated method stub
String _pre=pre+node.val; //将当前节点的值,附加到pre上面
if(node.left==null&&node.right==null) {//当前节点是叶子节点,结算
list.add(_pre);
return ;
}
if(node.left!=null)
f(_pre,node.left);
if(node.right!=null)
f(_pre,node.right);
}
List<String>list=new ArrayList<String>();
public static void main(String[] args) {
sumNumbers obj =new sumNumbers();
TreeNode<Integer> root = new TreeNode<>(1);
TreeNode<Integer> l = new TreeNode<>(2);
TreeNode<Integer> ll = new TreeNode<>(4);
TreeNode<Integer> lr = new TreeNode<>(7);
TreeNode<Integer> r = new TreeNode<>(3);
TreeNode<Integer> rr = new TreeNode<>(5);
TreeNode<Integer> rl = new TreeNode<>(8);
root.left = l;
root.right = r;
l.left = ll;
l.right = lr;
r.right = rr;
r.left = rl;
int sum =obj.SumNumbers(root);
System.out.println(sum);
}
}
节点封装
package _8题;
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;
}
}