zoukankan      html  css  js  c++  java
  • 剑指 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
    
  • 相关阅读:
    html例题——简历
    求值
    c#语句实例(排大小)
    3.6语言基础笔记
    2016.3.5进制间的转换
    3.26-1
    3.23(网页)
    3.23
    3.22
    3.20
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13661846.html
Copyright © 2011-2022 走看看