题目描述:
题解
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
题解1:
# 这个题解是与自己当时思路相接近的一种思路,参考别人的代码,进行了修改。
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0
depth = 0
n = 1
stack = [(root,n)]
while stack:
r,count = stack.pop()
if r.left:
stack.append((r.left,count+1))
if r.right:
stack.append((r.right,count+1))
if not r.right and not r.left :
depth = max(depth,count)
return depth
题解2:
# 比较简洁的一种实现
def maxDepth(self, root: TreeNode) -> int:
return max(self.maxDepth(root.left)+1,self.maxDepth(root.right)+1) if root else 0
总结
1、
DFS
2、
递归
3、
区别 .pop()和.pop(0)