二叉树索引:
root@jack-VirtualBox:~/test/tree# cat main.go
package main
import "fmt"
type Node struct {
Val int
Left *Node
Right *Node
}
var ss [][]string
func BinaryTreePath(root *Node, sss [][]string, path []string) {
strv := fmt.Sprintf("%d", root.Val)
path = append(path, strv)
// 找到一条完整的路径,存储到容器中
if root.Left == nil && root.Right == nil {
ss = append(ss, path)
}
if root.Left != nil {
BinaryTreePath(root.Left, ss, path)
}
if root.Right != nil {
BinaryTreePath(root.Right, ss, path)
}
}
func main() {
// 构建二叉树
root := &Node{
Val: 1,
Left: &Node{
Val: 2,
Left: nil,
Right: &Node{
Val: 4,
Left: nil,
Right: nil,
},
},
Right: &Node{
Val: 3,
Left: nil,
Right: nil,
},
}
// 获取二叉树所有路径
sss := [][]string{
}
p := []string{
}
BinaryTreePath(root, sss, p)
// 打印二叉树所有路径
for _, path := range ss {
fmt.Println(path)
}
}
root@jack-VirtualBox:~/test/tree#
执行:
root@jack-VirtualBox:~/test/tree# go run main.go
[1 2 4]
[1 3]
root@jack-VirtualBox:~/test/tree#