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
# -*- coding:utf-8 -*-
__author__ = 'yangxin_Ryan'
"""
Solutions:
我们可以利用递归的方式来深度遍历二叉树的叶子节点
* 当root为None,直接返回
* 当root不为空,并且没有左孩子以及右孩子,可以直接将结果存入res, 内容为 字符串间隔拼接,root ->
* 当root的左孩子为非空,我们以root.left为root,继续递归 self.dfs(root.left, path, res)
* 当root的右孩子为非空,我们以root.right为root,继续递归 self.dfs(root.right, path, res)
* 最后的 path.pop() 是由于我们开始将每个节点的val,保留下来了。path.append(str(root.val)),
方便拼接。
"""