思路
DFS
提交代码
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res=new ArrayList<>();
if(root==null) return res;
if(root.left==null&&root.right==null) {
res.add(Integer.toString(root.val));
return res;
}
StringBuilder curPath=new StringBuilder();
curPath.append(Integer.toString(root.val));
if(root.left!=null)
addPath(root.left,curPath,res);
if(root.right!=null)
addPath(root.right,curPath,res);
return res;
}
public void addPath(TreeNode root,StringBuilder path,List<String> res) {
int len=path.length();
path.append("->");
path.append(Integer.toString(root.val));
if(root.left==null&&root.right==null) {
res.add(path.toString());
}else {
if(root.left!=null)
addPath(root.left,path,res);
if(root.right!=null)
addPath(root.right,path,res);
}
path.delete(len, path.length());
}
}