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

@ -33,6 +33,7 @@ public class BinaryTreePaths{
} }
//力扣代码 //力扣代码
//leetcode submit region begin(Prohibit modification and deletion) //leetcode submit region begin(Prohibit modification and deletion)
/** /**
* Definition for a binary tree node. * Definition for a binary tree node.
* public class TreeNode { * public class TreeNode {
@ -50,14 +51,22 @@ public class BinaryTreePaths{
*/ */
class Solution { class Solution {
public List<String> binaryTreePaths(TreeNode root) { public List<String> binaryTreePaths(TreeNode root) {
if(root==null){ List<String> paths = new ArrayList<String>();
return null; dfs(root, "", paths);
return paths;
} }
List<String> list = new ArrayList<>();
if(root.left!=null){}
public void dfs(TreeNode root, String path, List<String> paths) {
return list; 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) //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