Loading
Leetcode / 257. Binary Tree Paths

Pick a programming language:

Here is the source code for the solution to this problem.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private void traverse(TreeNode root, String pathSoFar, List<String> list) {
        if (root == null) {
            return;
        }

        if (pathSoFar.length() > 0) {
            pathSoFar = pathSoFar + "->";
        }
        pathSoFar = pathSoFar + root.val;

        if (root.left == null && root.right == null) {
            // a leaf
            list.add(pathSoFar);
        }

        traverse(root.left, pathSoFar, list);
        traverse(root.right, pathSoFar, list);
    }
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new LinkedList<String>();
        traverse(root, "", list);
        return list;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: