leetcode 104.maximum-depth-of-binary-tree 二叉树的最大深度 python3

时间:2020-5-15

题目地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

题目难度:Easy

题目描述:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

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

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


思路1:递归,自底向上,dfs

代码段1:通过

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root == None:
            return 0
        else:
            left_depth = self.maxDepth(root.left)
            right_depth = self.maxDepth(root.right)
            return max(left_depth, right_depth) + 1

总结:

  1. 一开始想的是使用2^n-1索引位置确定层级,这样太复杂了,后边就换成递归了
  2. 递归还是写的少

思路2:递归,自顶向下【2020-8-3】

代码段2:通过

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        def top_down(node, depth):
            if node is None: return depth
            else:
                return max(top_down(node.left, depth + 1), top_down(node.right, depth + 1))
        return top_down(root, 0)

总结:

  1. “自顶向下”和“自底向上”的最终定义:

    在树的递归算法中,“自顶向下”指的是通过给函数传参的方式让信息流从根结点向下走,从而求得最终结果的过程。
    在树的递归算法中,“自底向上”指的是通过函数返回值让信息流从叶结点向上走,从而求得最终结果的过程。


思路3:使用队列,使用特殊元素区分每一层,树的层序遍历,bfs

代码段3:通过

from collections import deque
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root: return 0
        q, result = [root, None], 1
        while q:
            temp = q.pop(0)
            if (temp):
                if(temp.left):q.append(temp.left)
                if(temp.right):q.append(temp.right)
            elif q:
                q.append(None)
                result += 1
        return result

总结:

  1. 层序遍历使用这种方式好使

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值