meta data for this page
  •  

Binary Tree Paths

Leetcode


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

Example 1:

assets.leetcode.com_uploads_2021_03_12_paths-tree.jpg

Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]

Solution 1

Solution 1

public List<String> binaryTreePaths(TreeNode root) {
  List<String> output = new ArrayList<>();
  toLeaf(output, "", root);
  return output;
}
 
public void toLeaf(List<String> output, String path, TreeNode root) {
  if (root != null) {
    if (path.isEmpty()) {
      path += root.val;
    } else {
      path += ("->" + root.val);
    }
    if (root.left == null && root.right == null) {
      output.add(path);
      return;
    }
 
    if (root.left != null) {
      toLeaf(output, path, root.left);
    }
 
    if (root.right != null) {
      toLeaf(output, path, root.right);
    }
  }