![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/013fb47c01d3c242d26c995209c58ddd.png)
深度优先搜索
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e89369def1a3f2a78d4c1b905ac54a17.png)
1、加入—> (改了一下回溯)
class Solution {
List<String>paths=new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
dfs(root,"");
return paths;
}
void dfs(TreeNode root,String subpath){
if(root!=null){
StringBuilder builder=new StringBuilder(subpath);
builder.append(Integer.toString(root.val));
if(root.left==null&&root.right==null){
paths.add(builder.toString());
}
else{
builder.append("->");
dfs(root.left,builder.toString());
dfs(root.right,builder.toString());
}
}
}
}
2、只返回序列 没有—>,回溯
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a4c6e58a96dee871dce3e836cf8545e3.png)
class Solution {
List<String>paths=new ArrayList<>();
StringBuilder builder=new StringBuilder();
public List<String> binaryTreePaths(TreeNode root) {
dfs(root);
return paths;
}
void dfs(TreeNode root){
if(root!=null){
builder.append(Integer.toString(root.val));
if(root.left==null&&root.right==null){
paths.add(builder.toString());
}
else{
dfs(root.left);
dfs(root.right);
}
builder.deleteCharAt(builder.length()-1);
}
}
}
广度优先搜索
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a4c78a22a0db976effd8ebec67376351.png)
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
if (root == null) {
return paths;
}
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<String> pathQueue = new LinkedList<String>();
nodeQueue.offer(root);
pathQueue.offer(Integer.toString(root.val));
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.poll();
String path = pathQueue.poll();
if (node.left == null && node.right == null) {
paths.add(path);
} else {
if (node.left != null) {
nodeQueue.offer(node.left);
pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString());
}
if (node.right != null) {
nodeQueue.offer(node.right);
pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString());
}
}
}
return paths;
}
}