zoukankan      html  css  js  c++  java
  • leetcode104,111,543 求二叉树深度的dfs解法

    104.求二叉树的最大深度

    class Solution:
        def maxDepth(self, root: TreeNode) -> int:
            if root == None:
                return 0
            else:
                leftdepth = self.maxDepth(root.left)
                rightdepth = self.maxDepth(root.right)
                return max(leftdepth, rightdepth) + 1 #!!!关键在于+1

    111.求二叉树的最小深度

    class Solution:
        def minDepth(self, root: TreeNode) -> int:
            if not root:
                return 0
            if not root.left:
                return self.minDepth(root.right)+1
            if not root.right:
                return self.minDepth(root.left)+1
            return min(self.minDepth(root.left), self.minDepth(root.right))+1

    543.求二叉树的直径

    class Solution:
        def diameterOfBinaryTree(self, root: TreeNode) -> int:
            self.ans = 1
            def depth(node):
                if not node: return 0
                L = depth(node.left)
                R = depth(node.right)
                self.ans = max(self.ans, L+R+1)
                return max(L, R) + 1
            depth(root)
            return self.ans - 1
  • 相关阅读:
    记录一个异常
    ajax4
    ajax3
    ajax2
    ajax
    break与continue的区别
    Dom
    Dom元素的操作
    javascript (2)
    javascript
  • 原文地址:https://www.cnblogs.com/yawenw/p/12683921.html
Copyright © 2011-2022 走看看