Tree - 257. Binary Tree Paths

时间:2022-07-25
本文章向大家介绍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) + "->")
    }
}