列表

详情


257. 二叉树的所有路径

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

 

示例 1:

输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

示例 2:

输入:root = [1]
输出:["1"]

 

提示:

相似题目

路径总和 II

从叶结点开始的最小字符串

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { } };

golang 解法, 执行用时: 4 ms, 内存消耗: 2.5 MB, 提交时间: 2020-11-18 11:45:39

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func binaryTreePaths(root *TreeNode) []string {
    if root == nil {
        return []string{}
    }
    if root.Left == nil && root.Right == nil {
        return []string{strconv.Itoa(root.Val)}
    }
    var paths []string

    if root.Left != nil {
        for _, i := range binaryTreePaths(root.Left) {
            paths = append(paths, strconv.Itoa(root.Val) + "->" + i)
        }
    }
    if root.Right != nil {
        for _, i := range binaryTreePaths(root.Right) {
            paths = append(paths, strconv.Itoa(root.Val) + "->" + i)
        }
    }

    return paths
}

python3 解法, 执行用时: 44 ms, 内存消耗: 13.7 MB, 提交时间: 2020-11-02 16:13:45

# 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]:
        res = []
        if not root:
            return res
        stack = [(root, '')]
        while stack:
            node, road = stack.pop(0)
            if node.left == None and node.right == None:
                res.append(road + str(node.val))
            if node.left:
                stack.append((node.left, f'{road}{node.val}->'))
            if node.right:
                stack.append((node.right, f'{road}{node.val}->'))
        return res
            

python3 解法, 执行用时: 52 ms, 内存消耗: 13.5 MB, 提交时间: 2020-11-02 16:06:05

# 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 []
        if not root.left and not root.right:
            return [str(root.val)]
        paths = []
        if root.left:
            for i in self.binaryTreePaths(root.left):
                paths.append(str(root.val) + '->' + i)
        if root.right:
            for i in self.binaryTreePaths(root.right):
                paths.append(str(root.val) + '->' + i)
        return paths
            

上一题