我的个人微信公众号:Microstrong
微信公众号ID:MicrostrongAI
微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!
知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities
104. Maximum Depth of Binary Tree
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.
解题思路:
(1)递归解法
直观的方法是通过递归来解决问题。在这里,我们演示了 DFS(深度优先搜索)策略的示例。
已经AC的代码:
from typing import List
# 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
def getDepth(root):
if root is None:
return 0
left_high = getDepth(root.left)
right_high = getDepth(root.right)
return max(left_high, right_high) + 1
return getDepth(root)
if __name__ == "__main__":
root = TreeNode(3)
L1 = TreeNode(9)
R1 = TreeNode(20)
L2 = TreeNode(20)
R2 = TreeNode(7)
root.left = L1
root.right = R1
R1.left = L2
R1.right = R2
sol = Solution()
print(sol.maxDepth(root))
复杂度分析:
- 时间复杂度:我们每个结点只访问一次,因此时间复杂度为
,其中
是结点的数量。
- 空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用
次(树的高度),因此保持调用栈的存储将是
。但在最好的情况下(树是完全平衡的),树的高度将是
。因此,在这种情况下的空间复杂度将是
。
(2)迭代解法
我们还可以在栈的帮助下将上面的递归转换为迭代。
我们的想法是使用 DFS 策略访问每个结点,同时在每次访问时更新最大深度。
所以我们从包含根结点且相应深度为 1
的栈开始。然后我们继续迭代:将当前结点弹出栈并推入子结点。每一步都会更新深度。
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(1, root)]
depth = 0
while stack:
current_depth, root = stack.pop()
if root:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
Reference
【1】LeetCode 题解 | 104. 二叉树的最大深度,地址:https://zhuanlan.zhihu.com/p/49972754