Posts Binary Tree Paths
Post
Cancel

Binary Tree Paths

PROBLEM DESCRIPTION

Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.

Leetcode

SOLUTION

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
49
50
51
52
53
54
55
56
class Solution {
    
    public List<String> binaryTreePaths(TreeNode root) {
        pathHelper(root, new ArrayList<String>());
        return convertToListOfString(ans);
    }

    List<List<String>> ans = new ArrayList<List<String>>();

    public void pathHelper(TreeNode root, List<String> list){

        if(root == null){
            return;
        }

        //pre-order traversal
        list.add(root.val + "");

        pathHelper(root.left, list);
        pathHelper(root.right, list);

        //if leaf node, add to anser list
        if(root.left == null && root.right == null){
            ans.add(new ArrayList<String>(list));
        }

        //backtrack
        list.remove(list.size()-1);

    }

    public List<String> convertToListOfString(List<List<String>> list){
        
        List<String> ans = new ArrayList<>();

        StringBuffer sb = new StringBuffer();

        for(int i=0; i<list.size(); i++){

            List<String> t = list.get(i);

            for(int j=0; j<t.size(); j++){
                sb.append(t.get(j) + "->");
            }

            ans.add(new String(sb.toString().substring(0, sb.length()-2)));

            sb = new StringBuffer();

        }

        return ans;

    }

}
This post is licensed under CC BY 4.0 by the author.