LeetCode 题目-104.二叉树的最大深度/107.二叉树的层次遍历(python实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39884947/article/details/88984157

作为要准备踏入码农行业的人来说,要准备校招,怎么能不去刷刷LeetCode呢?

104.二叉树的最大深度

  • 题目要求

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

  • 例如
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。
  • 分析

方法一:利用深度优先搜素,递归判断树的深度

  def maxDepth(self, root):
        #深度优先搜索 使用递归
        if root is None:
            return 0
        else:
            left_height=self.maxDepth(root.left)
            right_height=self.maxDepth(root.right)
            return max(left_height,right_height)+1

方法二:利用层次(广度优先)遍历,用栈保存(当前深度,下一结点)。

    def maxdepth(self,root):
        stack=[]
        if root is not None:
            stack.append((1,root))
        depth=0

        while stack!=[]:
            current_depth,root=stack.pop()
            if root is not None:
                depth=max(depth,current_depth)
                stack.append((current_depth+1,root.left))
                stack.append((current_depth + 1, root.right))

        return depth
        


107.二叉树的层次遍历

  • 题目要求
    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

  • 例如

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
  • 分析

方法:模仿广度遍历,遍历同层次的直到同一层次结束

    def levelOrderBottom(self, root):
        # 广度优先
        if root is None:
            return []
            
        rang = []#返回结果的列表
        roots = []#下一层的结点
        roots.append(root)
        while roots:
            num = []
            length=len(roots)
            #获取每层结点的个数 这是与广度遍历不同的
            #因为这里同一层的数据要保存在同一个列表中
            for i in range(length):
                node = roots.pop(0)
                if node.val!=None:
                    num.append(node.val)
                if node.left is not None:
                    roots.append(node.left)
                if node.right is not None:
                    roots.append(node.right)

            rang.append(num)
        return rang[::-1]

猜你喜欢

转载自blog.csdn.net/qq_39884947/article/details/88984157