一、描述
二、题解
2.1 递归
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
2.2 利用栈
使用两个栈,一个记录深度,一个记录节点。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
stack = [root]
depth = [1]
max_ = 0
while(stack):
root = stack.pop(0)
num = depth.pop(0)
if not root.left and not root.right:# 当为叶子节点,深度停止增加
if num > max_:
max_ = num
if root.left:# 加入左部分,深度+1
stack.append(root.left)
depth.append(num+1)
if root.right: # 加入右部分,深度+1
stack.append(root.right)
depth.append(num+1)
return max_
如有问题或建议欢迎私信。
严禁私自转载,侵权必究。