257:二叉树的所有路径

This commit is contained in:
huangge1199@hotmail.com 2021-07-23 21:35:48 +08:00
parent ce8c27c625
commit 7271b462c7
3 changed files with 36 additions and 27 deletions

View File

@ -26,14 +26,15 @@ import java.util.ArrayList;
import java.util.List;
//257:二叉树的所有路径
public class BinaryTreePaths{
public class BinaryTreePaths {
public static void main(String[] args) {
//测试代码
Solution solution = new BinaryTreePaths().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
@ -48,18 +49,26 @@ public class BinaryTreePaths{
* }
* }
*/
class Solution {
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
if(root==null){
return null;
List<String> paths = new ArrayList<String>();
dfs(root, "", paths);
return paths;
}
List<String> list = new ArrayList<>();
if(root.left!=null){}
return list;
public void dfs(TreeNode root, String path, List<String> paths) {
if (root != null) {
path += root.val;
if (root.left == null && root.right == null) {
paths.add(path);
} else {
path += "->";
dfs(root.left, path, paths);
dfs(root.right, path, paths);
}
}
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long