Skip to content

Commit 832d877

Browse files
binary tree paths
1 parent b28adf5 commit 832d877

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

‎Common/src/utils/CommonUtils.java

+8
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,12 @@ public static void printMatrix(int[][] matrix) {
132132
System.out.println("----------------------------------------------------");
133133
}
134134

135+
public static void print(List<String> list) {
136+
System.out.println("----------------------------------------------------");
137+
for(String str : list){
138+
System.out.print(str + ", ");
139+
}
140+
System.out.println();
141+
}
142+
135143
}

‎EASY/src/easy/BinaryTreePaths.java

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package easy;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import utils.CommonUtils;
7+
import classes.TreeNode;
8+
9+
/**257. Binary Tree Paths Question Editorial Solution My Submissions
10+
Total Accepted: 59117
11+
Total Submissions: 191659
12+
Difficulty: Easy
13+
Given a binary tree, return all root-to-leaf paths.
14+
15+
For example, given the following binary tree:
16+
17+
1
18+
/ \
19+
2 3
20+
\
21+
5
22+
All root-to-leaf paths are:
23+
24+
["1->2->5", "1->3"]
25+
*/
26+
public class BinaryTreePaths {
27+
//a very typical/good question to test your recursion/dfs understanding.
28+
public List<String> binaryTreePaths_more_concise(TreeNode root) {
29+
List<String> paths = new ArrayList<String>();
30+
if(root == null) return paths;
31+
dfs(root, paths, "");
32+
return paths;
33+
}
34+
35+
private void dfs(TreeNode root, List<String> paths, String path) {
36+
if(root.left == null && root.right == null){
37+
paths.add(path + root.val);
38+
return;
39+
}
40+
path += root.val + "->";
41+
if(root.left != null) dfs(root.left, paths, path);
42+
if(root.right != null) dfs(root.right, paths, path);
43+
}
44+
45+
public static void main(String...strings){
46+
BinaryTreePaths test = new BinaryTreePaths();
47+
TreeNode root = new TreeNode(1);
48+
root.left = new TreeNode(2);
49+
root.left.right = new TreeNode(5);
50+
root.right = new TreeNode(3);
51+
List<String> res = test.binaryTreePaths(root);
52+
CommonUtils.print(res);
53+
}
54+
55+
public List<String> binaryTreePaths(TreeNode root) {
56+
List<String> paths = new ArrayList<String>();
57+
dfs(root, paths, new StringBuilder());
58+
return paths;
59+
}
60+
61+
private void dfs(TreeNode root, List<String> paths, StringBuilder sb) {
62+
if(root == null) return;
63+
if(root.left == null && root.right == null){
64+
sb.append(root.val);
65+
paths.add(sb.toString());
66+
return ;
67+
}
68+
sb.append(root.val + "->");
69+
String curr = sb.toString();
70+
if(root.left != null) dfs(root.left, paths, sb);
71+
sb.setLength(0);
72+
sb.append(curr);
73+
if(root.right != null) dfs(root.right, paths, sb);
74+
}
75+
}

0 commit comments

Comments
 (0)