Provide Best Programming Tutorials

257. Binary Tree Paths

Question

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

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output:

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

Explanation:

 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; }
 * }
 */
class Solution {
    List<String> rlist = new ArrayList();

    public List<String> binaryTreePaths(TreeNode root) {
        String currString = "";
        helper(root,currString);
        return rlist;
    }
    
    private void helper(TreeNode root,String currString){
        if(root == null) return;
        if(root.left == null && root.right == null){
            rlist.add(currString+root.val);
        }
        helper(root.left,currString + root.val+ "->");
        helper(root.right,currString  + root.val+"->");
    }
    
  
}

Leave a Reply

Close Menu