File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments