版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84924132
求最大树深
递归算法
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
# 递归 - 极简 - 开始:
if root is None:
return 0
f = self.maxDepth
return 1 + max(f(root.left), f(root.right))
1 行:
class Solution:
def maxDepth(self, root):
f = self.maxDepth
return 0 if root is None else 1 + max(f(root.left), f(root.right))
非递归算法
此算法的思路是,层序遍历二叉树,并统计树的层数,即高度。
if root is None:
return 0
last_level = [root]
h = 0
while last_level != []:
next_level = []
while last_level != []:
node = last_level.pop()
if node.left is not None:
next_level.append(node.left)
if node.right is not None:
next_level.append(node.right)
last_level = next_level
h += 1
return h
参考文献
- 这是印象笔记中的笔记,如果是在CSDN手机APP上查看此博客,请在印象笔记手机APP中搜索该参考文献:
https://app.yinxiang.com/shard/s44/nl/9329661/cf9069c3-cf9d-4f1d-b9d3-8346f19a2ebe; - 104. Maximum Depth of Binary Tree - LeetCode;
- https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/34198/Python-multiple-solutions-recursion-level-order-using-stack-and-level-order-using-queue;
- https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/169751/Python-Recursively-and-Iteratively。