博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode104.二叉树的最大深度 (BFS)+(递归)两种方法
阅读量:3934 次
发布时间:2019-05-23

本文共 979 字,大约阅读时间需要 3 分钟。

LeetCode104.二叉树的最大深度 (BFS)+(递归)两种方法

BFS

# 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 not root:            return 0        q = []        q.append(root)        ans = 0        while q:            tmp = []            for i in q:                if i.left:                    tmp.append(i.left)                if i.right:                    tmp.append(i.right)            ans += 1            q = tmp        return ans

递归

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

转载地址:http://pbrgn.baihongyu.com/

你可能感兴趣的文章
install libfreenect2 on ubuntu 16.04
查看>>
how to use automake to build files
查看>>
using matlab drawing line graph for latex
查看>>
How package finding works
查看>>
build opencv3.3.0 with VTK8.0, CUDA9.0 on ubuntu9.0
查看>>
how to compile kinfu_remake with cuda 9.0 opencv2.4.13.4
查看>>
qtcreator4.4.1中cmake 与cmake3.5.1本身generate出来的setting是有区别的解决方法
查看>>
CMake Useful Variables/Logging Useful Variables
查看>>
ubuntu下解决csdn网页打不开的问题
查看>>
MySQL server has gone away 问题的解决方法
查看>>
MySQL十大优化技巧
查看>>
PHP中文件读写操作
查看>>
php开发常识b_01
查看>>
PHP单例模式
查看>>
PHP项目设计
查看>>
memcache的安装及管理
查看>>
git 传输
查看>>
创建新项目
查看>>
inux下Git和gitosis的安装与配置
查看>>
1分钟学会用git管理代码
查看>>