[Solved] Given the root of a binary tree, return all root-to-leaf paths in any order.

Table of Contents

Question

Given the root of a binary tree, return all root-to-leaf paths in any order.

leaf is a node with no children.

Example 1:

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

Example 2:

Input: root = [1]
Output: ["1"]

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100

Python Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if root==None:return []
        stack = [[root,'']]
        res = []
        while stack:
            curr,path = stack.pop()
            if curr.left:stack.append([curr.left,path+str(curr.val)+'->'])
            if curr.right:stack.append([curr.right,path+str(curr.val)+'->'])
            if not curr.left and not curr.right:
                res.append(path+str(curr.val))
        
        return(res)

Leave a Reply

Your email address will not be published. Required fields are marked *