美文网首页
获取二叉树的最大深度

获取二叉树的最大深度

作者: 梁森的简书 | 来源:发表于2021-02-25 22:21 被阅读0次

    思路

    分别递归遍历根节点的左子树和右子树的最大深度,两者的最大值再加1就是二叉树的最大深度

    代码

    // 树的最大深度
        func maxDepth() -> Int {
            return maxDepth(node: root)
        }
        func maxDepth(node: TreeNode?) -> Int {
            if node == nil {
                return 0
            }
            var max = 0
            var maxL = 0
            var maxR = 0
            if node?.left != nil {
                maxL = maxDepth(node: node?.left)
            }
            if node?.right != nil {
                maxR = maxDepth(node: node?.right)
            }
            if maxL > maxR {
                max = maxL + 1
            } else {
                max = maxR + 1
            }
            return max
        }
    

    demo地址:https://github.com/yangguanghei/studyDateStructure

    相关文章

      网友评论

          本文标题:获取二叉树的最大深度

          本文链接:https://www.haomeiwen.com/subject/vblpfltx.html