首页 > 其他 > 详细

leetcode 二叉树的深度

时间:2020-05-10 19:00:51      阅读:52      评论:0      收藏:0      [点我收藏+]

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

leetcode 二叉树的深度

原文:https://www.cnblogs.com/yutingting/p/12768567.html

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