1、前言
题目描述2、思路
思路是按照回溯的方法来写的,本来叶子节点那有一个 list.remove(list.size() - 1) 的判断,但是后面又重复了,所以去掉了,只需要最后加就行。
3、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null){
return res;
}
dfs(root, new ArrayList<>());
return res;
}
private void dfs(TreeNode root, List<Integer> list){
if(root == null){
return;
}
list.add(root.val);
if(root.left == null && root.right == null){
String s = addRes(list);
res.add(s);
}
dfs(root.left, list);
dfs(root.right, list);
list.remove(list.size() - 1);
}
private String addRes(List<Integer> list){
String s = "";
for(int i = 0; i < list.size() - 1; i++){
s += list.get(i) + "->";
}
s += list.get(list.size() - 1);
return s;
}
}
网友评论