-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
48 lines (46 loc) · 1.11 KB
/
Copy pathsolution.java
File metadata and controls
48 lines (46 loc) · 1.11 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
40
41
42
43
44
45
46
47
48
// 257. Binary Tree Paths
// https://leetcode.com/problems/binary-tree-paths/
// Easy | Java | Accepted 2026-07-16
// Runtime 5 ms | Memory 50 MB
/**
* 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 {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
recurse(root, "");
return res;
}
public void recurse(TreeNode root, String ans)
{
TreeNode temp = root;
ans+=temp.val;
ans+="->";
if(temp.left==null&&temp.right==null)
{
ans = ans.substring(0,ans.length()-2);
res.add(ans);
return;
}
if(temp.left!=null)
{
recurse(temp.left, ans);
}
if(temp.right!=null)
{
recurse(temp.right, ans);
}
}
}