java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.csdn.net/grd_java/article/details/123063846
直接使用深度优先遍历 每次都将结点记录到路径字符串中 如果当前结点是叶子结点,说明一条路径遍历完成,直接添加到链表中 如果当前结点不是叶子结点,说明这条路径没有遍历完成,则添加->符号后,继续深度优先遍历
class Solution {
public List < String > binaryTreePaths ( TreeNode root) {
List < String > paths = new ArrayList < String > ( ) ;
constructPaths ( root, "" , paths) ;
return paths;
}
public void constructPaths ( TreeNode root, String path, List < String > paths) {
if ( root != null ) {
StringBuffer pathSB = new StringBuffer ( path) ;
pathSB. append ( Integer . toString ( root. val) ) ;
if ( root. left == null && root. right == null ) {
paths. add ( pathSB. toString ( ) ) ;
} else {
pathSB. append ( "->" ) ;
constructPaths ( root. left, pathSB. toString ( ) , paths) ;
constructPaths ( root. right, pathSB. toString ( ) , paths) ;
}
}
}
}