文章 224
评论 6
浏览 200760
Tree - 257. Binary Tree Paths

Tree - 257. Binary Tree Paths

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

思路:

题目意思是从root节点走到叶子节点一共有多少路径,采用递归求解,和先序遍历类似,找到叶子节点就把路径保存下来。

代码:

go:

/**

 * Definition for a binary tree node.

 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func binaryTreePaths(root *TreeNode) []string {
    var res []string
    if root == nil {
        return res
    }
    recursive(root, &res, strconv.Itoa(root.Val) + "->")
    return res
}

func recursive(node *TreeNode, res *[]string, s string) {
    if node.Left == nil && node.Right == nil {
        *res = append(*res, s[:len(s)-2])
    }
    
    if node.Left != nil {
        recursive(node.Left, res, s + strconv.Itoa(node.Left.Val) + "->")
    } 
    
    if node.Right != nil {
        recursive(node.Right, res, s + strconv.Itoa(node.Right.Val) + "->")
    }
}

标题:Tree - 257. Binary Tree Paths
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/19/1566219219451.html

Nothing just happens, it's all part of a plan.

取消