257. Binary Tree Paths


class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res=[]
ds=[]

self.rec(root,res,ds)
for i in range(len(res)):
res[i] = "->".join(res[i])
return(res)

def rec(self,root,res,ds):
if root ==None:
return
ds.append(str(root.val))

if root.left ==None and root.right==None:
res.append(ds.copy())
ds.pop(-1)
return
self.rec(root.left,res,ds)
self.rec(root.right,res,ds)
ds.pop(-1)

class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res=[]
if root:
self.rec(root,"",res)
return res

def rec(self,root,path,res):
path+=str(root.val)

if root.right==None and root.left ==None:
res.append(path)
return
if root.left:
self.rec(root.left,path+"->",res)
if root.right:
self.rec(root.right,path+"->",res)

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

All you need to know about Flutter App Development

Nature in computer science: Decision trees and Random forests

How Duolingo is Making You Translate the Internet For Free

Form Validation in Power Apps — Part 2

How to Add Branch Name in Git Commit?

Web Scraping — HTML

The Great Leetcode Hoax: Why Doing Leetcode Does Not Land You A Job?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

My Engineering Journey at Midtrans: Addressing Problems One Step at A Time

Banking Tailored to Minorities

LeetCode 10. Regular Expression Matching

example 1 start

Intro to APIs