Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5
All root-to-leaf paths are:

["1->2->5", "1->3"]

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> ans = new ArrayList<String>();
        if(root == null) return ans;

        List<Integer> curList = new ArrayList<Integer>();
        backtracking(ans, root, curList);
        return ans;
    }

    public void backtracking(List<String> ans, TreeNode root, List<Integer> curList) {
        curList.add(root.val);
        if(root.left == null && root.right == null) {
            // a leaf node
            StringBuilder sb = new StringBuilder();
            int start = 1;
            for(Integer node: curList) {
                if(start == 1) start = 0;
                else sb.append("->");
                sb.append(node);
            }
            ans.add(sb.toString());

        } else {
            if(root.left != null) backtracking(ans, root.left, curList);
            if(root.right != null) backtracking(ans, root.right, curList);
        }
        curList.remove(curList.size()-1);
    }
}

results matching ""

    No results matching ""