博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode104. Maximum Depth of Binary Tree (思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

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

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

3   / \  9  20    /  \   15   7

return its depth = 3.


返回树的深度,可以用DFS或者BFS算法,都很简单.

DFS:用maxdepth记录最大深度

class Solution:    def maxDepth(self, root: TreeNode) -> int:        if root is None: return 0        stack=[(root,1)]        maxdepth=1        while stack:            node,depth = stack.pop()            if depth>maxdepth:                maxdepth=depth            if node.left:                stack.append((node.left, depth+1))            if node.right:                stack.append((node.right, depth+1))        return maxdepth

BFS:

class Solution(object):    def maxDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        depth = 0        level = [root] if root else []        while level:            depth += 1            queue = []            for el in level:                if el.left:                    queue.append(el.left)                if el.right:                    queue.append(el.right)            level = queue                    return depth

 

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

你可能感兴趣的文章
PL/SQL学习笔记
查看>>
如何分析SQL语句
查看>>
结构化查询语言(SQL)原理
查看>>
SQL教程之嵌套SELECT语句
查看>>
日本語の記号の読み方
查看>>
计算机英语编程中一些单词
查看>>
JavaScript 经典例子
查看>>
判断数据的JS代码
查看>>
js按键事件说明
查看>>
AJAX 设计制作 在公司弄的 非得要做出这个养的 真晕!
查看>>
Linux 查看文件大小
查看>>
Java并发编程:线程池的使用
查看>>
redis单机及其集群的搭建
查看>>
Java多线程学习
查看>>
检查Linux服务器性能
查看>>
Java 8新的时间日期库
查看>>
Chrome开发者工具
查看>>
【LEETCODE】102-Binary Tree Level Order Traversal
查看>>
【LEETCODE】106-Construct Binary Tree from Inorder and Postorder Traversal
查看>>
【LEETCODE】202-Happy Number
查看>>