1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */var res []stringvar path []stringfunc binaryTreePaths(root *TreeNode) []string { res = make([]string,0) path = make([]string,0) if (root == nil) { return res } backTracking(root) return res}func backTracking(root *TreeNode){ // 终点 左右子节点都为nil if isLeafNode(root) { NodeValStr := strconv.Itoa(root.Val) path = append(path, NodeValStr) pathStr := strings.Join(path, "->") res = append(res, pathStr) return } // 前序遍历 中左右 // 遍历 每次递归的操作 NodeVal:= strconv.Itoa(root.Val)// 中 path = append(path, NodeVal) if root.Left != nil { // 左 backTracking(root.Left) path = path[:len(path)-1] } if root.Right != nil { // 右 backTracking(root.Right) path = path[:len(path)-1] }}func isLeafNode(node *TreeNode) bool{ if node.Right==nil && node.Left== nil && node!= nil{ return true } return false}