Tree - 257. Binary Tree Paths

2020-09-23 17:23:37 浏览数 (2)

257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

代码语言:javascript复制
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:

代码语言:javascript复制
/**

 * 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)   "->")
    }
}

0 人点赞