[LeetCode&Python] Problem 257. Binary Tree Paths

时间:2023-03-09 04:03:45
[LeetCode&Python] Problem 257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
/ \
2 3
\
5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 Iteration:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
stack=[]
stack.append((root,str(root.val)))
paths=[]
while stack:
node,path=stack.pop()
if not node.left and not node.right:
paths.append(path)
else:
if node.left:
stack.append((node.left,path+"->"+str(node.left.val)))
if node.right:
stack.append((node.right,path+"->"+str(node.right.val)))
return paths

  

Recursion:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
ans=[]
def isleaf(node):
if not node.right and not node.left:
return True
return False
def findPath(node,path):
if node:
path+=str(node.val)
if isleaf(node):
ans.append(path)
else:
path+="->"
findPath(node.left,path)
findPath(node.right,path)
path=""
findPath(root,path)
return ans