-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0257.java
More file actions
41 lines (35 loc) · 1.12 KB
/
_0257.java
File metadata and controls
41 lines (35 loc) · 1.12 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
package com.github.aditya;
import java.util.ArrayList;
import java.util.List;
public class _0257 {
// 10 ms, faster than 44.77%, memory 42.4 MB, less than 89.02%
class Solution {
List<String> result = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root != null)
traverse(root, "");
return result;
}
public void traverse(TreeNode node, String path) {
if (node.left == null && node.right == null)
result.add(path + node.val);
if (node.left != null)
traverse(node.left, path + node.val + "->");
if (node.right != null)
traverse(node.right, path + node.val + "->");
}
}
//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;
}
}
}