二叉树定义
节点值这里定义为int类型
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
求二叉树的深度
后续遍历方式:
- 二叉树结构如下:
3
/ \
9 20
/ \
15 7
- 二叉树初始化
head := &TreeNode{Val: 3}
head.Left = &TreeNode{Val: 9}
head.Right = &TreeNode{Val: 20}
head.Right.Left = &TreeNode{Val: 15}
head.Right.Right = &TreeNode{Val: 7}
- 定义求导函数
func getDeepthFunc(head * TreeNode) int {
deepth, res := 0, 0
if head == nil {
return 0
}
var f func(node *TreeNode)
f = func(node *TreeNode){
if node == nil {
return
}
deepth++
f(node.Left)
f(node.Right)
res = max(deepth, res)
deepth--
}
f(head)
return res
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
- 求导
fmt.Println(getDeepthFunc(head))
3