Binary Tree Paths

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

For example, given the following binary tree:
Screen Shot 2016-04-04 at 10.37.30 AM
All root-to-leaf paths are:
Screen Shot 2016-04-04 at 10.37.36 AM
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String> ();
        if (root == null) {
            return result;
        }
        int cur = root.val;
        findPaths(root, result, cur + "");
        return result;
    }

    private void findPaths(TreeNode root, List<String> result, String cur) {
        if (root.left == null && root.right == null) {
            result.add(cur);
            return;
        }

        if (root.left != null) {
            findPaths (root.left, result, cur + "->" + root.left.val);
        }

        if (root.right != null) {
            findPaths (root.right, result, cur + "->" + root.right.val);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s