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

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:

Machine Learning Projects
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)
Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 514

Leave a Reply

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