题目描述
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
题目大意:输出二叉树到所有叶子节点的完整路径
样例
Example:
python解法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
treePaths = []
r = []
def binary(self, root: TreeNode):
if not root:
return
self.r.append(str(root.val))
if not root.left and not root.right:
self.treePaths.append(self.r[:])
return
if root.left:
self.binary(root.left)
self.r.pop()
if root.right:
self.binary(root.right)
self.r.pop()
def binaryTreePaths(self, root: TreeNode) -> List[str]:
self.treePaths = []
self.r = []
self.binary(root)
return ['->'.join(val)for val in self.treePaths]
Runtime: 36 ms, faster than 87.02% of Python3 online submissions for Binary Tree Paths.
Memory Usage: 13.6 MB, less than 9.52% of Python3 online submissions for Binary Tree Paths.
题后反思:
- 我自己想到的方法不太好,代码量较多还不好理解
- 找到一个我觉得写得挺好的,贴出来并写一写我的理解
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: return []
result= [ str(root.val)+"->" + path for path in self.binaryTreePaths(root.left)]
result+= [ str(root.val)+"->" + path for path in self.binaryTreePaths(root.right)]
return result or [str(root.val)] # if empty return leaf itself
别人四行代码完美解决。说说字节对这四行代码的理解。
访问节点为空时,直接返回[],否则递归寻找左子树,并将碰到的节点转换成字符串放在列表result中,同时继续递归寻找右子树,将碰到的节点转换成字符串放在列表再次加到result中。result中存放的是根节点到叶子节点的路径的字符串。
注意:当访问到叶子节点的时候,result结果为[ ]
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步