257:二叉树的所有路径
This commit is contained in:
parent
ce8c27c625
commit
7271b462c7
@ -26,40 +26,49 @@ 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;
|
||||
* TreeNode left;
|
||||
* TreeNode right;
|
||||
* TreeNode() {}
|
||||
* TreeNode(int val) { this.val = val; }
|
||||
* TreeNode(int val, TreeNode left, TreeNode right) {
|
||||
* this.val = val;
|
||||
* this.left = left;
|
||||
* this.right = right;
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
class Solution {
|
||||
public List<String> binaryTreePaths(TreeNode root) {
|
||||
if(root==null){
|
||||
return null;
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* public class TreeNode {
|
||||
* int val;
|
||||
* TreeNode left;
|
||||
* TreeNode right;
|
||||
* TreeNode() {}
|
||||
* TreeNode(int val) { this.val = val; }
|
||||
* TreeNode(int val, TreeNode left, TreeNode right) {
|
||||
* this.val = val;
|
||||
* this.left = left;
|
||||
* this.right = right;
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
class Solution {
|
||||
public List<String> binaryTreePaths(TreeNode root) {
|
||||
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
Loading…
Reference in New Issue
Block a user