二叉树索引:
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
[1 2 4]
[1 3]
root@jack-VirtualBox:~/test/tree
|