剑指 Offer 55



方法一: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
原文地址:https://www.cnblogs.com/panweiwei/p/13661846.html