首页 > 其他 > 详细

剑指 Offer 55 - I. 二叉树的深度

时间:2020-09-13 17:23:56      阅读:73      评论:0      收藏:0      [点我收藏+]

技术分享图片

方法一:BFS模板的应用。

总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html

class Solution(object):
    # 思路:层序模板。
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        ans = []
        stack = [root]
        while stack:
            l = len(stack)
            temp = []
            for i in range(l):
                node = stack.pop(0)
                temp.append(node.val)
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
            ans.append(temp)
        return len(ans)

方法二:DFS。

class Solution(object):
    # 思路:树的深度 = 根的左子树深度+1 或 右子树深度+1
    def maxDepth2(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        leftDepth = self.maxDepth2(root.left)
        rightDepth = self.maxDepth2(root.right)
        return leftDepth + 1 if leftDepth > rightDepth else rightDepth + 1

剑指 Offer 55 - I. 二叉树的深度

原文:https://www.cnblogs.com/panweiwei/p/13661846.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!