二叉树深度求导golang实现

二叉树定义

节点值这里定义为int类型

type TreeNode struct {
    Val int
    Left *TreeNode
    Right *TreeNode
}

求二叉树的深度

后续遍历方式:

  1. 二叉树结构如下:
    3
   / \
  9  20
    /  \
   15   7
  1. 二叉树初始化
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}
  1. 定义求导函数
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
}
  1. 求导
fmt.Println(getDeepthFunc(head))

结果为3

你可能感兴趣的:(二叉树深度求导golang实现)