257. Binary Tree Paths
求二叉树的所有路径,dfs返回值为空。dfs返回值为空的情况基本都是修改引用(比如说结果数组),因此需要声明一个结果数组之后另外写一个dfs。然后分情况讨论,对于中间节点path = path + root.val + "->"
,对于最后一个节点,不需要加箭头,并且将每条路径的字符串加入结果。对于空节点,直接返回(不执行)。
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
dfs(root, "", res);
return res;
}
public void dfs(TreeNode root, String path, List<String>res) {
if (root == null) return;
if (root.left == null && root.right == null) {
res.add(path + root.val);
return;
}
path += root.val + "->";
dfs(root.left, path, res);
dfs(root.right, path, res);
}