meta data for this page
Binary Tree Paths
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:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
jump to: Search / User Tools / Main Content / Change Content Width
Software Quality Engineering & Beyond
You are here: SQE & Beyond » Interview Questions » Algorithm Interview Questions » Binary Tree Paths
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:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
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); } }