题解 | #二叉树根节点到叶子节点的所有路径和,dfs#
二叉树根节点到叶子节点的所有路径和
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 int sumNumbers (TreeNode root) {
if(root == null) return 0 ;
List<String> list = new ArrayList<>() ;
dfs(root , "" , list) ;
int count = 0 ;
for(String str : list) {
count += Integer.parseInt(str) ;
}
return count ;
}
//深搜,把完整的路径保留在list中
public void dfs(TreeNode root , String tmp , List<String> list) {
if(root.left == null && root.right == null) {
list.add(tmp+root.val) ;
return ;
}
if(root.left != null) {
dfs(root.left , tmp + root.val , list) ;
}
if(root.right != null) {
dfs(root.right , tmp + root.val , list) ;
}
}
}
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录
