题解 | #二叉树根节点到叶子节点的所有路径和#回溯算法
二叉树根节点到叶子节点的所有路径和
http://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public static ArrayList<LinkedList<Integer>> res = new ArrayList<>();
public int sumNumbers (TreeNode root) {
if(root == null) return 0;
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(root.val);
printTree(root,ll);
int finalresult = 0;
for(int i = 0;i<res.size();i++){
LinkedList<Integer> lres = res.get(i);
int lsum = 0;
while(!lres.isEmpty()){
lsum = lsum *10 + lres.removeFirst();
}
finalresult += lsum;
}
return finalresult;
}
public static void printTree(TreeNode node,LinkedList<Integer> ll){
if(node.left == null && node.right == null){
LinkedList<Integer> lres = new LinkedList<>();
for(Integer x:ll){
lres.add(x);
}
res.add(lres);
System.out.println(lres.toString());
return;
}
if(node.left != null){
ll.add(node.left.val);
printTree( node.left, ll);
ll.removeLast();
}
if(node.right !=null){
ll.add(node.right.val);
printTree( node.right, ll);
ll.removeLast();
}
}
}
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public static ArrayList<LinkedList<Integer>> res = new ArrayList<>();
public int sumNumbers (TreeNode root) {
if(root == null) return 0;
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(root.val);
printTree(root,ll);
int finalresult = 0;
for(int i = 0;i<res.size();i++){
LinkedList<Integer> lres = res.get(i);
int lsum = 0;
while(!lres.isEmpty()){
lsum = lsum *10 + lres.removeFirst();
}
finalresult += lsum;
}
return finalresult;
}
public static void printTree(TreeNode node,LinkedList<Integer> ll){
if(node.left == null && node.right == null){
LinkedList<Integer> lres = new LinkedList<>();
for(Integer x:ll){
lres.add(x);
}
res.add(lres);
System.out.println(lres.toString());
return;
}
if(node.left != null){
ll.add(node.left.val);
printTree( node.left, ll);
ll.removeLast();
}
if(node.right !=null){
ll.add(node.right.val);
printTree( node.right, ll);
ll.removeLast();
}
}
}