Skip to content

Commit 7fa3342

Browse files
Binary Tree Paths: Accepted
1 parent b393590 commit 7fa3342

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ My accepted leetcode solutions to some of the common interview problems.
227227
- [Maximum Binary Tree](problems/src/tree/MaximumBinaryTree.java) (Medium)
228228
- [Find Bottom Left Tree Value](problems/src/tree/FindBottomLeftTreeValue.java) (Medium)
229229
- [Diameter of Binary Tree](problems/src/tree/DiameterOfBinaryTree.java) (Easy)
230+
- [Binary Tree Paths](problems/src/tree/BinaryTreePaths.java) (Easy)
230231

231232
#### [Two Pointers](problems/src/two_pointers)
232233

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package tree;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Created by gouthamvidyapradhan on 09/12/2017.
8+
* Given a binary tree, return all root-to-leaf paths.
9+
10+
For example, given the following binary tree:
11+
12+
1
13+
/ \
14+
2 3
15+
\
16+
5
17+
All root-to-leaf paths are:
18+
19+
["1->2->5", "1->3"]
20+
*/
21+
public class BinaryTreePaths {
22+
23+
public class TreeNode {
24+
int val;
25+
TreeNode left;
26+
TreeNode right;
27+
TreeNode(int x) { val = x; }
28+
}
29+
30+
public List<String> binaryTreePaths(TreeNode root) {
31+
List<String> result = new ArrayList<>();
32+
new BinaryTreePaths().inorder(root, result, "");
33+
return result;
34+
}
35+
36+
private void inorder(TreeNode node, List<String> list, String path){
37+
if(node != null){
38+
if(node.left == null && node.right == null){
39+
list.add(path + node.val);
40+
} else {
41+
inorder(node.left, list, path + node.val + "->");
42+
inorder(node.right, list, path + node.val + "->");
43+
}
44+
}
45+
}
46+
47+
}

0 commit comments

Comments
 (0)