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
posted @ 2020-05-10 17:18  YTiing  阅读(175)  评论(0编辑  收藏  举报