[go语言算法获取树的深度]

2020-07-28  本文已影响0人  Ucan先生

递归写法

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
     if root==nil{
         return 0
     }
     if root.Left == nil && root.Right == nil {
         return 1
     }
     leftDepth := maxDepth(root.Left)
     rightDepth := maxDepth(root.Right)
     if leftDepth > rightDepth{
         return leftDepth+1
     }else{
         return rightDepth+1
     }
}

非递归写法

BFS tmpList用作示意

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root == nil{
        return 0
    }
    quene := []*TreeNode{}
    tmpList := []*TreeNode{}
    tmpList = append(tmpList,root)
    depth := 0
    for len(quene) > 0 || len(tmpList) >0 {
        //队列为空当前层入队
        if len(quene) == 0{
            quene = append(quene,tmpList...)
            depth++
            tmpList = []*TreeNode{}
            continue
        }else{
            //队列不为空则出队
        node := quene[0]
        if node.Left!=nil{
            tmpList = append(tmpList,node.Left)
        }
        if node.Right!=nil{
            tmpList = append(tmpList,node.Right)
        }
        if len(quene) > 0 {
            quene = quene[1:]
        }
    }
}
    return depth
}
上一篇 下一篇

猜你喜欢

热点阅读