【Leetcode】257—Binary Tree Paths
2019-07-16 本文已影响0人
Gaoyt__
一、题目描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
二、代码实现
实现一:基于栈
# 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 []
res = []
stack = [(root, "")]
while stack:
node, ls = stack.pop()
if not node.left and not node.right:
res.append(ls + str(node.val))
if node.left:
stack.append((node.left, ls + str(node.val) + '->'))
if node.right:
stack.append((node.right, ls + str(node.val) + '->'))
return res
实现二:DFS
# 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]
"""
def dfs(root, path, res):
if not root.left and not root.right:
res.append(path + str(root.val))
return res
if root.left:
dfs(root.left, path + str(root.val) + "->", res)
if root.right:
dfs(root.right, path + str(root.val) + "->", res)
if not root: return []
res = []
dfs(root, "", res)
return res