-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePath.java
More file actions
39 lines (39 loc) · 1.26 KB
/
binaryTreePath.java
File metadata and controls
39 lines (39 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 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 new ArrayList<>(); // Return an empty list if the root is null
}
// Create a list of strings
List<String> stringList = new ArrayList<>();
helper(root,"",stringList); // Pass an empty string as the current path
return stringList;
}
public void helper(TreeNode root,String currentPath, List<String> str){
if(root==null){
return;
}
if(root.left==null && root.right==null){
// If it's a leaf node, add the current path to the list
str.add(currentPath+root.val);
return;
}
// recursively traverse the left and right subtree
helper(root.left,currentPath+root.val+ "->",str);
helper(root.right,currentPath+root.val+ "->",str);
}
}