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

递归写法

/**
 * 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
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。