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 "]
Example 2:
Input: root = [1] Output: [ "1 "]
Constraints:
[1, 100].-100 <= Node.val <= 100program main
! Solves the problem: Given the `root` of a binary tree, return all root-to-leaf paths in any order.
implicit none
type :: TreeNode
integer :: val
type(TreeNode), pointer :: left => null(), right => null()
end type TreeNode
type(TreeNode), target :: root
character(len=:), allocatable :: str
call solve(root)
contains
subroutine solve(root)
! Solve the problem
type(TreeNode), intent(inout) :: root
type(TreeNode), pointer :: curr
integer :: i
if (associated(root%left)) then
call solve(root%left)
end if
if (associated(root%right)) then
call solve(root%right)
end if
if (.not. associated(root%left) .and. .not. associated(root%right)) then
write (str, "(I0)") root%val
do while (associated(curr))
write (str, "(A, I0)") trim(str), curr%val
curr => curr%left
end do
print '(A)', trim(str) // " "
end if
end subroutine solve
end program main
temp.f95:24:33:
24 | call solve(root%left)
| 1
Error: SUBROUTINE ‘solve’ at (1) cannot be called recursively, as it is not RECURSIVE
temp.f95:27:34:
27 | call solve(root%right)
| 1
Error: SUBROUTINE ‘solve’ at (1) cannot be called recursively, as it is not RECURSIVE
module binary_tree_paths
implicit none
contains
function binary_tree_paths_helper(root, path) result(paths)
type(binary_tree_node), pointer, intent(in) :: root
character(len=:), allocatable :: path
character(len=:), allocatable :: paths(:)
if (associated(root)) then
path = trim(path) // to_string(root%val)
if (root%left == null() .and. root%right == null()) then
paths = [path]
else
paths = [path]
paths = [paths, binary_tree_paths_helper(root%left, path // "->" // to_string(root%val))]
paths = [paths, binary_tree_paths_helper(root%right, path // "->" // to_string(root%val))]
end if
else
paths = [path]
end if
end function binary_tree_paths_helper
function binary_tree_paths(root) result(paths)
type(binary_tree_node), pointer, intent(in) :: root
character(len=:), allocatable :: path
character(len=:), allocatable :: paths(:)
path = ""
paths = binary_tree_paths_helper(root, path)
end function binary_tree_paths
function to_string(val) result(str)
integer, intent(in) :: val
character(len=:), allocatable :: str
write (str, "(i0)") val
end function to_string
end module binary_tree_paths
program test_binary_tree_paths
use binary_tree_paths, only : binary_tree_paths, binary_tree_node
implicit none
type(binary_tree_node), pointer :: root
character(len=:), allocatable :: paths(:)
! Example 1
root = binary_tree_node([1, 2, 3, null(), 5])
paths = binary_tree_paths(root)
call assert(paths == ["1->2->5", "1->3"])
! Example 2
root = binary_tree_node([1])
paths = binary_tree_paths(root)
call assert(paths == ["1"])
contains
subroutine assert(condition)
logical, intent(in) :: condition
if (.not. condition) then
write (*,*) "Assertion failed"
stop 1
end if
end subroutine assert
end program test_binary_tree_paths
temp.f95:9:27:
9 | type(binary_tree_node), pointer, intent(in) :: root
| 1
Error: Derived type ‘binary_tree_node’ at (1) is being used before it is defined
temp.f95:14:45:
14 | path = trim(path) // to_string(root%val)
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:15:18:
15 | if (root%left == null() .and. root%right == null()) then
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:19:59:
19 | paths = [paths, binary_tree_paths_helper(root%left, path // "->" // to_string(root%val))]
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:20:59:
20 | paths = [paths, binary_tree_paths_helper(root%right, path // "->" // to_string(root%val))]
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:22:8:
22 | else
| 1
Error: Unexpected ELSE statement at (1)
temp.f95:24:7:
24 | end if
| 1
Error: Expecting END FUNCTION statement at (1)
temp.f95:28:26:
28 | function binary_tree_paths(root) result(paths)
| 1
Error: MODULE attribute of ‘binary_tree_paths’ conflicts with PROCEDURE attribute at (1)
temp.f95:30:27:
30 | type(binary_tree_node), pointer, intent(in) :: root
| 1
Error: Derived type ‘binary_tree_node’ at (1) is being used before it is defined
temp.f95:31:41:
31 | character(len=:), allocatable :: path
| 1
Error: Unexpected data declaration statement in CONTAINS section at (1)
temp.f95:32:45:
32 | character(len=:), allocatable :: paths(:)
| 1
Error: Unexpected data declaration statement in CONTAINS section at (1)
temp.f95:34:13:
34 | path = ""
| 1
Error: Unexpected assignment statement in CONTAINS section at (1)
temp.f95:35:48:
35 | paths = binary_tree_paths_helper(root, path)
| 1
Error: Unexpected assignment statement in CONTAINS section at (1)
temp.f95:37:3:
37 | end function binary_tree_paths
| 1
Error: Expecting END MODULE statement at (1)
temp.f95:7:38:
7 | function binary_tree_paths_helper(root, path) result(paths)
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:52:48:
52 | use binary_tree_paths, only : binary_tree_paths, binary_tree_node
| 1
Error: The name ‘binary_tree_paths’ at (1) has already been used as an external module name
temp.f95:55:23:
55 | type(binary_tree_node), pointer :: root
| 1
Error: Derived type ‘binary_tree_node’ at (1) is being used before it is defined
temp.f95:59:41:
59 | root = binary_tree_node([1, 2, 3, null(), 5])
| 1
Error: NULL() at (1) cannot appear in an array constructor
temp.f95:60:30:
60 | paths = binary_tree_paths(root)
| 1
Error: Symbol ‘root’ at (1) has no IMPLICIT type
temp.f95:61:32:
61 | call assert(paths == ["1->2->5", "1->3"])
| 1
Error: Different CHARACTER lengths (7/4) in array constructor at (1)
temp.f95:64:7:
64 | root = binary_tree_node([1])
| 1
Error: Function ‘binary_tree_node’ at (1) has no IMPLICIT type
temp.f95:66:12:
66 | call assert(paths == ["1"])
| 1
Error: Rank mismatch in argument ‘condition’ at (1) (scalar and rank-1)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def binary_tree_paths(root: TreeNode):
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
paths = []
for path in binary_tree_paths(root.left):
paths.append(str(root.val) + "->" + path)
for path in binary_tree_paths(root.right):
paths.append(str(root.val) + "->" + path)
return paths
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is null, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the binary_tree_paths() function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.
#include <vector>
#include <string>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
std::vector<std::string> binaryTreePaths(TreeNode* root) {
std::vector<std::string> paths;
if (!root)
return paths;
if (!root->left && !root->right) {
paths.push_back(std::to_string(root->val));
return paths;
}
for (const std::string &path : binaryTreePaths(root->left)) {
paths.push_back(std::to_string(root->val) + "->" + path);
}
for (const std::string &path : binaryTreePaths(root->right)) {
paths.push_back(std::to_string(root->val) + "->" + path);
}
return paths;
}
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is null, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the binary_tree_paths() function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.