zoukankan      html  css  js  c++  java
  • leetcode 二叉树的深度

    leetcode 104.二叉树的最大深度

    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    class Solution(object):
        # 递归
        def maxDepth(self, root):
            if not root: return 0
            left = self.maxDepth(root.left) + 1
            right = self.maDepth(root.right) + 1
            return max(left, right)
        
        # 迭代-BFS
        def maxDepth(self, root):
            if not root: return 0
            stack = [(1, root)]
            while stack:
                depth, node = stack.pop(0)
                if node.left: stack.append((depth+1, node.left))
                if node.right: stack.append((depth+1, node.right))
            return depth
    
        # 迭代-DFS(右孩子先入栈-左孩子再入栈)
        def maxDepth(self, root):
            if not root: return 0
            depth, stack = 0, [(1, root)]
            while stack:
                cur_depth, node = stack.pop()
                depth = max(depth, cur_depth)
                if node.right: stack.append((cur_depth+1, node.right))
                if node.left: stack.append((cur_depth+1, node.left))
            return depth
    

    leetcode 111.二叉树的最小深度

    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    class Solution(object):
        # 递归
        def minDepth(self, root):
            if not root: return 0
            left = self.minDepth(root.left)
            right = self.minDepth(root.right)
            return left+right+1 if not left or not right else min(left, right)+1
        
        # 迭代-BFS
        def minDepth(self, root):
            if not root: return 0
            stack = [(1, root)]
            while stack:
                depth, node = stack.pop(0)
                # 广度优先,输出遇到的第一个叶子节点的长度即为最小的深度
                if not node.left and not node.right: return depth  
                if node.left: stack.append((depth+1, node.left))
                if node.right: stack.append((depth+1,node.right))
    
        # 迭代-DFS
        def minDepth(self, root):
            if not root: return 0
            stack = [(1, root)]
            depth = float("inf")
            while stack:
                cur_depth, node = stack.pop()
                # 比较当前的深度和每个叶子节点的深度取最小
                if not node.left and not node.right: depth = min(depth, cur_depth)
                if node.right: stack.append((cur_depth+1, node.right))
                if node.left: stack.append((cur_depth+1, node.left))
            return depth
    
  • 相关阅读:
    [NOIp2016] 天天爱跑步
    状压DP小拼盘
    DP × KMP
    KMP算法 详解+模板
    [NOI2014] 起床困难综合症
    [洛谷P3391] 文艺平衡树 (Splay模板)
    START
    【C】单链表的实现
    【数据结构】动态顺序表
    C语言实现扫雷程序
  • 原文地址:https://www.cnblogs.com/yutingting/p/12768567.html
Copyright © 2011-2022 走看看